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 only have a single character.
Isn't there a better way (concerning performance) for checking if it's a whitespace?
If I do something like this. I would miss white spaces like tabs I guess?
if (ch == ' ') {
...
}
This small function will allow you to enter a string of variable length as an argument and it will report "true" if the first character is white space or "false" otherwise. You can easily put any character from a string into the function using the indexOf or charAt methods. Examples:
This will work
or you can also use this indexOf():
@jake 's answer above -- using the
trim()
method -- is the best option. If you have a single character ch as a hex number: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 usingindexOf()
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
If you only want to test for certain whitespace characters, do so manually, otherwise, use a regular expression, ie
Keep in mind that different browsers match different characters, eg in Firefox,
\s
is equivalent to (source)whereas in Internet Explorer, it should be (source)
The MSDN page actually forgot the space ;)
this covers spaces, tabs and newlines:
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...
how about this one : ((1L << ch) & ((ch - 64) >> 31) & 0x100002600L) != 0L