在JavaScript中替换所有函数

时间:2009-12-02 04:29:42

标签: javascript regex

我收到一个字符串"test+test1+asd.txt",我想将其转换为"test test1 asd.txt"

我正在尝试使用函数str = str.replace("/+/g"," ");

但这不起作用

的问候, 与Hemant

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:0)

如果你打算使用正则表达式,那么

+1 S.Mark's answer,但对于单个字符替换,你可以轻松使用:

yourString = yourString.split("+").join(" ");

答案 2 :(得分:0)

这是一个简单的javascript函数,可替换所有内容:

function replaceAll (originalstring, exp1, exp2) {
//Replaces every occurrence of exp1 in originalstring with exp2 and returns the new string.

    if (exp1 == "") {
        return;  //Or else there will be an infinite loop because of i = i - 1 (see later).
        }

    var len1 = exp1.length;
    var len2 = exp2.length;
    var res = "";  //This will become the new string

    for (i = 0; i < originalstring.length; i++) {
        if (originalstring.substr(i, len1) == exp1) {  //exp1 found
            res = res + exp2;  //Append to res exp2 instead of exp1
            i = i + (len1 - 1);  //Skip the characters in originalstring that have been just replaced
        }
        else {//exp1 not found at this location; copy the original character into the new string
            res = res + originalstring.charAt(i);
        }
    }
    return res;
}