How to check for string having only spaces in javascript
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
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.