BrunoLM
BrunoLM

Reputation: 100331

How to replace all characters in a string?

I have a string that is passed by parameter and I have to replace all occurrences of it in another string, ex:

function r(text, oldChar, newChar)
{
    return text.replace(oldChar, newChar); // , "g")
}

The characters passed could be any character, including ^, |, $, [, ], (, )...

Is there a method to replace, for example, all ^ from the string I ^like^ potatoes with $?

Upvotes: 2

Views: 1524

Answers (3)

Elias Dorneles
Elias Dorneles

Reputation: 23806

Use a RegExp object instead of a simple string:

text.replace(new RegExp(oldChar, 'g'), newChar);

Upvotes: 0

jValdron
jValdron

Reputation: 3418

If you simply pass '^' to the JavaScript replace function it should be treated as a string and not as a regular expression. However, using this method, it will only replace the first character. A simple solution would be:

function r(text, oldChar, newChar)
{
    var replacedText = text;

    while(text.indexOf(oldChar) > -1)
    {
        replacedText = replacedText.replace(oldChar, newChar);
    }

    return replacedText;
}

Upvotes: 1

aefxx
aefxx

Reputation: 25249

function r(t, o, n) {
    return t.split(o).join(n);
}

Upvotes: 9

Related Questions