How can I remove extra white space in a string in JavaScript?

前端 未结 9 1041
故里飘歌
故里飘歌 2021-02-09 01:47

How can I remove extra white space (i.e. more than one white space character in a row) from text in JavaScript?

E.g

match    the start using.

相关标签:
9条回答
  • 2021-02-09 02:16

    Using regular expression.

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

    Here is jsfiddle for this

    0 讨论(0)
  • 2021-02-09 02:18

    This can be done also with javascript logic.
    here is a reusable function I wrote for that task.
    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>
    
    0 讨论(0)
  • 2021-02-09 02:26

    Try this regex

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

    or as a function

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

    Here is a working demo

    0 讨论(0)
提交回复
热议问题