Regex to replace multiple spaces with a single space

后端 未结 23 2324
北恋
北恋 2020-11-22 10:00

Given a string like:

\"The dog      has a long   tail, and it     is RED!\"

What kind of jQuery or JavaScript magic can be used to keep spaces to only o

相关标签:
23条回答
  • 2020-11-22 10:15
    var text = `xxx  df dfvdfv  df    
                         dfv`.split(/[\s,\t,\r,\n]+/).filter(x=>x).join(' ');
    

    result:

    "xxx df dfvdfv df dfv"
    
    0 讨论(0)
  • 2020-11-22 10:16

    Since you seem to be interested in performance, I profiled these with firebug. Here are the results I got:

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

    This is on Firefox, running 100k string replacements.

    I encourage you to do your own profiling tests with firebug, if you think performance is an issue. Humans are notoriously bad at predicting where the bottlenecks in their programs lie.

    (Also, note that IE 8's developer toolbar also has a profiler built in -- it might be worth checking what the performance is like in IE.)

    0 讨论(0)
  • 2020-11-22 10:19
    var myregexp = new RegExp(/ {2,}/g);
    
    str = str.replace(myregexp,' ');
    
    0 讨论(0)
  • 2020-11-22 10:21

    Here is an alternate solution if you do not want to use replace (replace spaces in a string without using replace javascript)

    var str="The dog      has a long   tail, and it     is RED!";
    var rule=/\s{1,}/g;
    
    str = str.split(rule).join(" "); 
    
    document.write(str);

    0 讨论(0)
  • 2020-11-22 10:21

    We can use the following regex explained with the help of sed system command. The similar regex can be used in other languages and platforms.

    Add the text into some file say test

    manjeet-laptop:Desktop manjeet$ cat test
    "The dog      has a long   tail, and it     is RED!"
    

    We can use the following regex to replace all white spaces with single space

    manjeet-laptop:Desktop manjeet$ sed 's/ \{1,\}/ /g' test
    "The dog has a long tail, and it is RED!"
    

    Hope this serves the purpose

    0 讨论(0)
  • 2020-11-22 10:23
    var str = "The      dog        has a long tail,      and it is RED!";
    str = str.replace(/ {2,}/g,' ');
    

    EDIT: If you wish to replace all kind of whitespace characters the most efficient way would be like that:

    str = str.replace(/\s{2,}/g,' ');
    
    0 讨论(0)
提交回复
热议问题