Reputation: 109
I am getting a string "test+test1+asd.txt"
and i want to convert it into "test test1 asd.txt"
I am trying to use function str = str.replace("/+/g"," ");
but this is not working
regards, hemant
Upvotes: 2
Views: 2036
Reputation: 1
Here is a simple javascript function that replaces all:
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;
}
Upvotes: 0
Reputation: 35051
+1 for S.Mark's answer if you're intent on using a regular expression, but for a single character replace you could easily use:
yourString = yourString.split("+").join(" ");
Upvotes: 0