Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a single character is a whitespace?

Tags:

javascript

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 == ' ') {     ... } 
like image 457
edbras Avatar asked Sep 30 '09 08:09

edbras


People also ask

How do I know if a character is space bash?

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.

How do you check if a character is a white space in C#?

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.

How do you find the whitespace of a string?

You can use charAt() function to find out spaces in string.


2 Answers

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 ;)

like image 50
Christoph Avatar answered Sep 23 '22 14:09

Christoph


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'); 
like image 35
jake Avatar answered Sep 23 '22 14:09

jake