Regex to replace multiple spaces with a single space

后端 未结 23 2347
北恋
北恋 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:03

    More robust:

    function trim(word)
    {
        word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces
        return word.replace(/^\s+|\s+$/g, '');      // remove leading/trailing spaces
    }
    
    0 讨论(0)
  • 2020-11-22 10:03

    Also a possibility:

    str.replace( /\s+/g, ' ' )
    
    0 讨论(0)
  • 2020-11-22 10:03

    Try this to replace multiple spaces with a single space.

    <script type="text/javascript">
        var myStr = "The dog      has a long   tail, and it     is RED!";
        alert(myStr);  // Output 'The dog      has a long   tail, and it     is RED!'
    
        var newStr = myStr.replace(/  +/g, ' ');
        alert(newStr);  // Output 'The dog has a long tail, and it is RED!'
    </script>
    

    Read more @ Replacing Multiple Spaces with Single Space

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

    Jquery has trim() function which basically turns something like this " FOo Bar " into "FOo Bar".

    var string = "  My     String with  Multiple lines    ";
    string.trim(); // output "My String with Multiple lines"
    

    It is much more usefull because it is automatically removes empty spaces at the beginning and at the end of string as well. No regex needed.

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

    I suggest

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

    for just spaces
    OR

    string = string.replace(/(\s)+/g,"$1");
    

    for turning multiple returns into a single return also.

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

    A more robust method: This takes care of also removing the initial and trailing spaces, if they exist. Eg:

    // NOTE the possible initial and trailing spaces
    var str = "  The dog      has a long   tail, and it     is RED!  "
    
    str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
    
    // str -> "The dog has a long tail, and it is RED !"
    

    Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was only trimming those into single spaces, like: " The ... RED! ", which is not what you will typically need.

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