Check if a single character is a whitespace?

后端 未结 9 1190
清酒与你
清酒与你 2021-02-06 21:21

What is the best way to check if a single character is a whitespace?

I know how to check this through a regex.

But I am not sure if this is the best way if I onl

相关标签:
9条回答
  • 2021-02-06 22:00

    While it's not entirely correct, I use this pragmatic and fast solution:

    if (ch.charCodeAt(0) <= 32) {...
    
    0 讨论(0)
  • 2021-02-06 22:00

    @jake 's answer above -- using the trim() method -- is the best option. If you have a single character ch as a hex number:

    String.fromCharCode(ch).trim() === ""
    

    will return true for all whitespace characters.

    Unfortunately, comparison like <=32 will not catch all whitespace characters. For example; 0xA0 (non-breaking space) is treated as whitespace in Javascript and yet it is > 32. Searching using indexOf() with a string like "\t\n\r\v" will be incorrect for the same reason.

    Here's a short JS snippet that illustrates this: https://repl.it/@saleemsiddiqui/JavascriptStringTrim

    0 讨论(0)
  • 2021-02-06 22:08

    this covers spaces, tabs and newlines:

    if ((ch == ' ') || (ch == '\t') || (ch == '\n'))
    

    this should be best for performance. put the whitespace character you expect to be most likely, first.

    if performance is really important, probably best to consider the bigger picture than individual operations like this...

    0 讨论(0)
提交回复
热议问题