簡體   English   中英

Javascript正則表達式僅在匹配之外替換

[英]Javascript Regular Expression to replace only outside of a match

我希望能夠替換但僅限於字符串的某個部分

var message = "this is my :) `funky :)` string with a funky `goal :D` live is good :D";

var map = {
    "<3": "\u2764\uFE0F",
    "</3": "\uD83D\uDC94",
    ":D": "\uD83D\uDE00",
    ":)": "\uD83D\uDE03",
    ":-)": "\uD83D\uDE03",
    ";)": "\uD83D\uDE09",
    ":(": "\uD83D\uDE12",
    ":p": "\uD83D\uDE1B",
    ";p": "\uD83D\uDE1C",
    ":'(": "\uD83D\uDE22",
    ":S": "\ud83d\ude1f",
    ":$": "\ud83d\ude33",
    ":@": "\ud83d\ude21"
};
for (var i in map) {
    var regex = new RegExp(i.replace(/([()[{*+.$^\\|?])/g, '\\$1'), 'gim');
    message = message.replace(regex, map[i]);
}

我想要的預期輸出是

this is my \uD83D\uDE0f `funky :)` string with a funky `goal :D` live is good \uD83D\uDE00

您可以構造一個在map所有.keys之間交替的正則表達式,首先轉義鍵,以便將正則表達式中具有特殊含義的字符(如$ )解析為文字字符而不是特殊的正則表達式字符。

還可以使用匹配反引號的模式,后跟非反引號字符,然后是另一個反引號 - 這樣所有反引號包圍的子字符串也將匹配。

使用構造的模式對輸入字符串調用.replace並使用替換函數。 如果匹配以反引號開始,則匹配是您根本不想修改的內容,因此只需返回匹配即可。 否則,與之匹配的是的關鍵之一map ,在該鍵,返回相關的值map

 const message = "this is my :) `funky :)` string with a funky `goal :D` live is good :D"; const map = { "<3": "\❤\️", "</3": "\?\?", ":D": "\?\?", ":)": "\?\?", ":-)": "\?\?", ";)": "\?\?", ":(": "\?\?", ":p": "\?\?", ";p": "\?\?", ":'(": "\?\?", ":S": "\?\?", ":$": "\?\?", ":@": "\?\?" }; const escape = str => str.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'); const backtickPattern = '`[^`]*`'; const pattern = new RegExp( backtickPattern + '|' + Object.keys(map) .map(escape) .join('|'), 'g' ); const output = message.replace(pattern, match => { if (match.startsWith('`')) { // backtick, don't perform any replacements: return match; } return map[match]; }); console.log(output);

暫無
暫無

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

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