Check if a single character is a whitespace?
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 == ' ') {
...
}
If you only want to test for certain whitespace characters, do so manually, otherwise, use a regular expression, ie
/\s/.test(ch)
Keep in mind that different browsers match different characters, eg in Firefox, \s
is equivalent to (source)
[ \f\n\r\t\v\u00A0\u2028\u2029]
whereas in Internet Explorer, it should be (source)
[ \f\n\r\t\v]
The MSDN page actually forgot the space ;)
The regex approach is a solid way to go. But here's what I do when I'm lazy and forget the proper regex syntax:
str.trim() === '' ? alert('just whitespace') : alert('not whitespace');
I have referenced the set of whitespace characters matched by PHP's trim function without shame (minus the null byte, I have no idea how well browsers will handle that).
if (' \t\n\r\v'.indexOf(ch) > -1) {
// ...
}
This looks like premature optimization to me though.
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...