NewDev
NewDev

Reputation: 109

ReplaceAll function in javascript

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

Answers (3)

user11717468
user11717468

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

NickFitz
NickFitz

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

YOU
YOU

Reputation: 123841

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

Upvotes: 9

Related Questions