如何减少前导和尾随空格

时间:2014-02-05 06:15:38

标签: javascript

var str = "    abcd    ";

if(str.match(/\ /)) { 
    document.writeln("String Empty");
} else {
    document.writeln("Length :  ");
    document.writeln(str.length);
}

上面的代码总是返回一个空字符串,尽管它们之间有字符。

我需要砍掉前面和后面的空格。

2 个答案:

答案 0 :(得分:1)

// 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"

答案 1 :(得分:0)

使用修剪并检查长度:

if (!str.trim().length) { 
  document.writeln("String Empty");
}
else {
 document.writeln("Length : ");
 document.writeln(str.trim().length);
}