Replace all spaces in a string with '+'

This question already has an answer here:

  • How to replace all occurrences of a string in JavaScript? 41 answers

  • 这是一个不需要regex的选择:

    var str = 'a b c';
    var replaced = str.split(' ').join('+');
    

    You need the /g (global) option, like this:

    var replaced = str.replace(/ /g, '+');
    

    You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.


    var str = 'a b c';
    var replaced = str.replace(/s/g, '+');
    
    链接地址: http://www.djcxy.com/p/16830.html

    上一篇: 替换字符串中的所有逗号

    下一篇: 用'+'替换字符串中的所有空格