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

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

提交回复
热议问题