Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for string having only spaces in javascript

Tags:

javascript

In my code i need to write an if else block-

when the variable `currentValue` is holding only spaces -> certain code

But i don't know how to write this condition as currentValue can be a string of any size. It can hold " ", " " etc. if i write currentValue!=" " it checks for single space.

like image 804
Shruti Rawat Avatar asked Jul 08 '13 10:07

Shruti Rawat


People also ask

How do I check if a string contains only spaces?

Using the isspace() method This method tells us whether the string contains only spaces or if any other character is present. This method returns true if the given string is only made up of spaces otherwise it returns false. The method returns true even if the string is made up of characters like \t, .

How do you check if string is empty with spaces?

1. String isBlank() Method. This method returns true if the given string is empty or contains only white space code points, otherwise false . It uses Character.

How do you filter out spaces in JavaScript?

JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.

How do you count strings with spaces?

To count the spaces in a string:Use the split() method to split the string on each space. Access the length property on the array and subtract 1. The result will be the number of spaces in the string.


2 Answers

Could look like

if( !currentValue.trim().length ) {
    // only white-spaces
}

docs: trim

Even if its very self-explanatory; The string referenced by currentValue gets trimmed, which basically means all white-space characters at the beginning and the end will get removed. If the entire string consists of white-space characters, it gets cleaned up alltogether, that in turn means the length of the result is 0 and !0 will be true.

About performance, I compared this solution vs. the RegExp way from @mishik. As it turns out, .trim() is much faster in FireFox whereas RegExp seems way faster in Chrome.

http://jsperf.com/regexp-vs-trim-performance

like image 93
jAndy Avatar answered Sep 30 '22 14:09

jAndy


Simply:

if (/^\s*$/.test(your_string)) {
  // Only spaces
}

To match space only:

if (/^ *$/.test(your_string)) {
  // Only spaces
}

Explanation: /^\s*$/ - match a beginning of a string, then any number of whitespaces (space, newline, tab, etc...), then end of string. /^ *$/ - same, but only for spaces.

If you do not want to match empty string: replace * with + to make sure that at least one character is present.

like image 33
mishik Avatar answered Sep 30 '22 14:09

mishik