我有一个包含多个空格的字符串。我想用加号来代替。我想我可以用

var str = 'a b c';
var replaced = str.replace(' ', '+');

但它只替换了第一个事件。我怎么能让它替换所有的事件?


当前回答

您需要寻找一些replaceAll选项

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

这是一个执行replaceAll的正则表达式。

function ReplaceAll(Source, stringToFind, stringToReplace) {
    var temp = Source;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;
}

String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
    var temp = this;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;

};

其他回答

您需要寻找一些replaceAll选项

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

这是一个执行replaceAll的正则表达式。

function ReplaceAll(Source, stringToFind, stringToReplace) {
    var temp = Source;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;
}

String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
    var temp = this;
    var index = temp.indexOf(stringToFind);

    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }

    return temp;

};

你需要/g(全局)选项,像这样:

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

你可以在这里试试。与大多数其他语言不同,默认情况下,JavaScript只替换第一次出现的内容。

递归地做这个:

public String replaceSpace(String s){
    if (s.length() < 2) {
        if(s.equals(" "))
            return "+";
        else
            return s;
    }
    if (s.charAt(0) == ' ')
        return "+" + replaceSpace(s.substring(1));
    else
        return s.substring(0, 1) + replaceSpace(s.substring(1));
}

使用全局搜索字符串。g标志

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

来源:replaceAll函数

这里有一个不需要regex的替代方案:

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