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

前端 未结 9 968
故里飘歌
故里飘歌 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:00

    Sure, using a regex:

    var str = "match    the start using. Remove the extra space between match and the";
    str = str.replace(/\s/g, ' ')
    
    0 讨论(0)
  • 2021-02-09 02:03
      function RemoveExtraSpace(value)
      {
        return value.replace(/\s+/g,' ');
      }
    
    0 讨论(0)
  • 2021-02-09 02:03

    Just do,

    var str = "match    the start using. Remove the extra space between match and the";
    str = str.replace( /\s\s+/g, ' ' );
    
    0 讨论(0)
  • 2021-02-09 02:11

    Use regex. Example code below:

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

    For better performance, use below regex:

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

    Profiling with firebug resulted in following:

    str.replace(/ +/g, ' ')        ->  790ms
    str.replace(/ +/g, ' ')       ->  380ms
    str.replace(/ {2,}/g, ' ')     ->  470ms
    str.replace(/\s\s+/g, ' ')     ->  390ms
    str.replace(/ +(?= )/g, ' ')    -> 3250ms
    
    0 讨论(0)
  • 2021-02-09 02:14

    See string.replace on MDN

    You can do something like this:

    var string = "Multiple  spaces between words";
    string = string.replace(/\s+/,' ', g);
    
    0 讨论(0)
  • 2021-02-09 02:14
    myString = Regex.Replace(myString, @"\s+", " "); 
    

    or even:

    RegexOptions options = RegexOptions.None;
    Regex regex = new Regex(@"[ ]{2,}", options);     
    tempo = regex.Replace(tempo, @" ");
    
    0 讨论(0)
提交回复
热议问题