简体   繁体   中英

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 $ ?

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

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

使用RegExp对象而不是简单的字符串:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM