簡體   English   中英

如何替換字符串中的所有字符?

[英]How to replace all characters in a string?

我有一個由參數傳遞的字符串,我必須在另一個字符串中替換所有出現的字符串,例如:

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

傳遞的字符可以是任何字符,包括^| $[]() ......

是否有一種方法可以替換,例如,所有^來自字符串I ^like^ potatoes$

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

如果您只是將'^'傳遞給JavaScript替換函數,則應將其視為字符串而不是正則表達式。 但是,使用此方法,它只會替換第一個字符。 一個簡單的解決方案是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM