Regular expression for removing whitespaces

前端 未结 6 1540
悲&欢浪女
悲&欢浪女 2020-12-29 09:12

I have some text which looks like this -

\"    tushar is a good      boy     \"

Using javascript I want to remove all the extra white spac

相关标签:
6条回答
  • 2020-12-29 09:56

    Try this:

    str.replace(/\s+/g, ' ').trim()
    

    If you don't have trim add this.

    Trim string in JavaScript?

    0 讨论(0)
  • 2020-12-29 09:58

    Since everyone is complaining about .trim(), you can use the following:

    str.replace(/\s+/g,' ' ).replace(/^\s/,'').replace(/\s$/,'');

    JSFiddle

    0 讨论(0)
  • 2020-12-29 10:05

    Try:

    str.replace(/^\s+|\s+$/, '')
       .replace(/\s+/, ' ');
    
    0 讨论(0)
  • 2020-12-29 10:06

    This can be done in a single String#replace call:

    var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
    
    // gives: "tushar is a good boy"
    
    0 讨论(0)
  • 2020-12-29 10:09

    try

    var str = "    tushar is a good      boy     ";
    str = str.replace(/^\s+|\s+$/g,'').replace(/(\s\s\s*)/g, ' ');
    

    first replace is delete leading and trailing spaces of a string.

    0 讨论(0)
  • 2020-12-29 10:12

    This works nicely:

    function normalizeWS(s) {
        s = s.match(/\S+/g);
        return s ? s.join(' ') : '';
    }
    
    • trims leading whitespace
    • trims trailing whitespace
    • normalizes tabs, newlines, and multiple spaces to a single regular space
    0 讨论(0)
提交回复
热议问题