javascript中的ReplaceAll函数

javascript中的ReplaceAll函数,javascript,regex,Javascript,Regex,我得到一个字符串“test+test1+asd.txt”,我想把它转换成“testtest1 asd.txt” 我试图使用函数str=str.replace(“/+//g”,”) 但这是行不通的 问候,, hemant+1如果您打算使用正则表达式,但对于单个字符替换,您可以轻松使用: yourString = yourString.split("+").join(" "); 下面是一个简单的javascript函数,用于替换所有: function replaceAll (originalst

我得到一个字符串
“test+test1+asd.txt”
,我想把它转换成
“testtest1 asd.txt”

我试图使用函数
str=str.replace(“/+//g”,”)

但这是行不通的

问候,, hemant

+1如果您打算使用正则表达式,但对于单个字符替换,您可以轻松使用:

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

下面是一个简单的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;
}
函数replaceAll(originalstring,exp1,exp2){
//将originalstring中出现的每个exp1替换为exp2并返回新字符串。
如果(exp1==“”){
return;//否则,由于i=i-1,将有一个无限循环(见下文)。
}
变量len1=exp1.length;
var len2=exp2.length;
var res=”“;//这将成为新字符串
对于(i=0;i
在正则表达式中,
+
有特殊的含义。所以,你必须用反斜杠来逃避它。这就是s.Mark的正则表达式起作用的原因<代码>\+
并且在Javascript中没有将正则表达式放在字符串中,这是替换失败的第二个原因。+1但是IMHO需要解释,比如Edmassa:)如果正则表达式只有一个固定字符,为什么要使用正则表达式?
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;
}