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? Commented Dec 2, 2009 at 8:39

3 Answers 3

9
str = str.replace(/\+/g," ");
Sign up to request clarification or add additional context in comments.

3 Comments

The + has special meaning in RegEx. So, you have to escape it with a backslash. That's why S.Mark's RegEx works. \+
And you don't put Regex in strings in Javascript, that is the second reason your replace failed.
+1 but IMHO needs explanation, like the one from EndangeredMassa :)
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(" ");

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.