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.
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, .
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.
JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.
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.
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.
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