如何在JavaScript中删除字符串中的额外空格?

时间:2013-10-03 09:28:49

标签: javascript

如何从JavaScript中的文本中删除多余的空格(即一行中多个空白字符)?

E.g

match    the start using.

如何删除“match”和“the”之间的所有空格?

9 个答案:

答案 0 :(得分:25)

使用正则表达式。示例代码如下:

var string = 'match    the start using. Remove the extra space between match and the';
string = string.replace(/\s{2,}/g, ' ');

为了获得更好的性能,请使用以下正则表达式:

string = string.replace(/ +/g, ' ');

使用萤火虫进行分析后得出以下结果:

str.replace(/ +/g, ' ')        ->  790ms
str.replace(/ +/g, ' ')       ->  380ms
str.replace(/ {2,}/g, ' ')     ->  470ms
str.replace(/\s\s+/g, ' ')     ->  390ms
str.replace(/ +(?= )/g, ' ')    -> 3250ms

答案 1 :(得分:5)

请参阅MDN上的string.replace

您可以这样做:

var string = "Multiple  spaces between words";
string = string.replace(/\s+/,' ', g);

答案 2 :(得分:1)

  function RemoveExtraSpace(value)
  {
    return value.replace(/\s+/g,' ');
  }

答案 3 :(得分:1)

myString = Regex.Replace(myString, @"\s+", " "); 

甚至:

RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);     
tempo = regex.Replace(tempo, @" ");

答案 4 :(得分:1)

使用正则表达式。

var string = "match    the start using. Remove the extra space between match and the";
string = string.replace(/\s+/g, " ");

这是jsfiddle for this

答案 5 :(得分:1)

这也可以使用javascript逻辑来完成。
这是我为该任务编写的可重用函数。
LIVE DEMO

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div>result: 
      <span id="spn">
      </span>
    </div>
    <input type="button" value="click me" onClick="ClearWhiteSpace('match    the start using.  JAVASCRIPT    CAN    BE   VERY  FUN')"/>
    <script>
      function ClearWhiteSpace(text) {
        var result = "";
        var newrow = false;
        for (var i = 0; i < text.length; i++) {
          if (text[i] === "\n") {
            result += text[i];
            // add the new line
            newrow = true;
          }
          else if (newrow == true && text[i] == " ") {
            // do nothing
          }
          else if (text[i - 1] == " " && text[i] == " " && newrow == false) {
            // do nothing
          }
          else {
            newrow = false;
            if (text[i + 1] === "\n" && text[i] == " ") {
              // do nothing it is a space before a new line
            }
            else {
              result += text[i];
            }
          }
        }
        alert(result);
        document.getElementById("spn").innerHTML = result;
        return result;
      }
    </script>
  </body>
</html>

答案 6 :(得分:0)

做,

var str = "match    the start using. Remove the extra space between match and the";
str = str.replace( /\s\s+/g, ' ' );

答案 7 :(得分:0)

当然,使用正则表达式:

var str = "match    the start using. Remove the extra space between match and the";
str = str.replace(/\s/g, ' ')

答案 8 :(得分:-1)

试试这个正则表达式

var st = "hello world".replace(/\s/g,'');

或作为一种功能

    function removeSpace(str){
      return str.replace(/\s/g,'');
    }

这是一个有效的demo