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 == ' ') { ... }
In BASH, you can use POSIX character classes to match whitespace with [[:space:]] . The [[:space:]] will match any whitespace character. +1, It's worth noting that this will match all whitespace (tab, newline etc) chars not only just a single space.
IsWhiteSpace(String, Int32) Method. This method is used to check whether a character in the specified string at the specified position can be categorized as whitespace or not. It returns True when the character is a whitespace character otherwise it returns False.
You can use charAt() function to find out spaces in string.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With