Reputation: 35
var str = " abcd ";
if(str.match(/\ /)) {
document.writeln("String Empty");
} else {
document.writeln("Length : ");
document.writeln(str.length);
}
The above code always returns an empty string although it has characters in between.
I need to chop the leading and trailing white spaces.
Upvotes: 0
Views: 113
Reputation: 64657
Use trim and check the length:
if (!str.trim().length) {
document.writeln("String Empty");
}
else {
document.writeln("Length : ");
document.writeln(str.trim().length);
}
Upvotes: 0
Reputation: 987
// Remove leading and trailing whitespace
// Requires jQuery
var str = " a b c d e f g ";
var newStr = $.trim(str);
// "a b c d e f g"
// Remove leading and trailing whitespace
// JavaScript RegEx
var str = " a b c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
// "a b c d e f g"
// Remove all whitespace
// JavaScript RegEx
var str = " a b c d e f g ";
var newStr = str.replace(/\s+/g, '');
// "abcdefg"
Upvotes: 1