更新时间:2023-02-12 19:15:06
我希望将替换项存储为对象中的键值对或成对的数组.无论采用哪种格式,都可以通过使用|
替换连接要替换的值来动态创建正则表达式.然后为replace
提供一个回调函数,并使用其match参数作为键在swaps
对象中查找其对应对.
I'd prefer to store replacements as key-value pairs in an object or as an array of pairs. Regardless of the format, you can dynamically create a regex by joining the values you want to replace using |
alternation. Then give replace
a callback function and use its match parameter as a key to look up its corresponding pair in the swaps
object.
const s = "I am Java";
const swaps = {am: "love", Java: "JS"};
const pattern = new RegExp(Object.keys(swaps).join("|"), "g");
console.log(s.replace(pattern, m => swaps[m]));
要处理不区分大小写的替换,请确保swaps
中的所有键都是小写字母(通过编程方式或手动方式,具体取决于用法),并在键入之前将匹配项小写:
To handle case-insensitive replacements, ensure all keys in swaps
are lowercase (either programmatically or manually, depending on usage) and lowercase the matches before keying in:
const s = "I am Java";
const swaps = {am: "love", java: "JS"};
const pattern = new RegExp(Object.keys(swaps).join("|"), "gi");
console.log(s.replace(pattern, m => swaps[m.toLowerCase()]));