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!
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.
Yes, also your regex will match if there are just spaces.
\s is the regex character for whitespace. It matches spaces, new lines, carriage returns, and tabs.
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.
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)
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