简体   繁体   English

Javascript正则表达式仅在匹配之外替换

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

I want to be able to replace but limit to a certain portion of the string i basically want to leave anything inside double ` untouched and only replace out side of these conditions我希望能够替换但仅限于字符串的某个部分

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

The expected output i want is我想要的预期输出是

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

You can construct a regular expression that alternates between all the .keys of the map , escaping the keys first so that the characters with a special meaning in a regular expression (like $ ) get parsed as literal characters rather than special regex characters.您可以构造一个在map所有.keys之间交替的正则表达式,首先转义键,以便将正则表达式中具有特殊含义的字符(如$ )解析为文字字符而不是特殊的正则表达式字符。

Also alternate with a pattern that matches a backtick followed by non-backtick characters, followed by another backtick - that way all backtick-enclosed substrings will be matched as well.还可以使用匹配反引号的模式,后跟非反引号字符,然后是另一个反引号 - 这样所有反引号包围的子字符串也将匹配。

Call .replace on the input string with the constructed patter and use a replacer function.使用构造的模式对输入字符串调用.replace并使用替换函数。 If the match starts with a backtick, then the match is something you don't want to modify at all, so just return the match.如果匹配以反引号开始,则匹配是您根本不想修改的内容,因此只需返回匹配即可。 Otherwise, the match is one of the keys of map , so return the associated value at that key in map :否则,与之匹配的是的关键之一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