8

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

例如

match    the start using.

如何删除“match”和“the”之间的所有空格,但只有一个空格?

4

9 回答 9

29

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

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

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

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

使用 firebug 进行分析导致以下结果:

str.replace(/ +/g, ' ')        ->  790ms
str.replace(/ +/g, ' ')       ->  380ms
str.replace(/ {2,}/g, ' ')     ->  470ms
str.replace(/\s\s+/g, ' ')     ->  390ms
str.replace(/ +(?= )/g, ' ')    -> 3250ms
于 2013-10-03T09:31:46.260 回答
4

请参阅MDN 上的string.replace

你可以这样做:

var string = "Multiple  spaces between words";
string = string.replace(/\s+/,' ', g);
于 2013-10-03T09:31:57.683 回答
1

做就是了,

var str = "match    the start using. Remove the extra space between match and the";
str = str.replace( /\s\s+/g, ' ' );
于 2013-10-03T09:32:47.170 回答
1
  function RemoveExtraSpace(value)
  {
    return value.replace(/\s+/g,' ');
  }
于 2013-10-03T09:33:26.080 回答
1
myString = Regex.Replace(myString, @"\s+", " "); 

甚至:

RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);     
tempo = regex.Replace(tempo, @" ");
于 2013-10-03T09:34:10.517 回答
1

使用正则表达式。

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

这是jsfiddle

于 2013-10-03T09:35:42.870 回答
0

当然,使用正则表达式:

var str = "match    the start using. Remove the extra space between match and the";
str = str.replace(/\s/g, ' ')
于 2013-10-03T09:32:50.220 回答
0

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

<!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>
于 2019-02-09T05:10:09.127 回答
-1

试试这个正则表达式

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

或作为一个函数

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

这是一个工作演示

于 2013-10-03T09:34:00.057 回答