2

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

1
  • 1
    Why use a regular expression if it's only one fixed character? Dec 2, 2009 at 8:39

3 Answers 3

9
str = str.replace(/\+/g," ");
3
  • 3
    The + has special meaning in RegEx. So, you have to escape it with a backslash. That's why S.Mark's RegEx works. \+ Dec 2, 2009 at 4:39
  • 1
    And you don't put Regex in strings in Javascript, that is the second reason your replace failed. Dec 2, 2009 at 4:44
  • +1 but IMHO needs explanation, like the one from EndangeredMassa :) Dec 2, 2009 at 12:32
0

+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(" ");
0

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.