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.
// 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"
Use trim and check the length:
if (!str.trim().length) {
document.writeln("String Empty");
}
else {
document.writeln("Length : ");
document.writeln(str.trim().length);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.