var str = "    abcd    ";
if(str.match(/\ /)) { 
    document.writeln("String Empty");
} else {
    document.writeln("Length :  ");
    document.writeln(str.length);
}上面的代码总是返回一个空字符串,尽管它之间有字符。
我需要去掉前导和尾随的空格。
发布于 2014-02-05 14:19:49
// 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"发布于 2014-02-05 14:20:09
使用trim并检查长度:
if (!str.trim().length) { 
  document.writeln("String Empty");
}
else {
 document.writeln("Length : ");
 document.writeln(str.trim().length);
}https://stackoverflow.com/questions/21569923
复制相似问题