Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex only spaces - javascript

I need to filter a field composed of only spaces; something like:

if (word == /((\s)+)/ ) return 'no name'

but it doesn't work ... any other ideas? thank you for your ideas!

like image 536
Marco Avatar asked Jun 24 '11 17:06

Marco


People also ask

How do I check if input is only spaces?

To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0 . If the string has a length of 0 after calling the trim method, then the string contains only spaces.

Can regex include spaces?

Yes, also your regex will match if there are just spaces.

How do I allow blank space in regex?

\s is the regex character for whitespace. It matches spaces, new lines, carriage returns, and tabs.

How do you check if a string has a space?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.


1 Answers

You should use if(/^\s+$/.test(word)). (Notice the ^ and $, without them the regex will hold for any string that has at least a space-like character)

like image 117
Gabi Purcaru Avatar answered Oct 08 '22 02:10

Gabi Purcaru