如何将 str.replace 与 JavaScript 中的许多 find/replace 对一起使用
How to use str.replace with many find/replace pairs in JavaScript
我需要 JavaScript 中的一个函数,它以一个字符串作为输入,用相应的值替换许多子字符串,然后 returns 结果。例如:
function findreplace(inputStr) {
const values = {"a": "A",
"B": "x",
"c": "C"};
// In this example, if inputStr is "abc", then outputStr should be "AbC".
return outputStr
}
我知道如何单独查找和替换,但我想知道是否有一种简单的方法可以同时处理多对(区分大小写的)值。
谢谢!
您可以join keys
构建正则表达式,然后replace
相应地
function findreplace(inputStr) {
let values = { "a": "A", "B": "x", "c": "C" };
let regex = new RegExp("\b" + Object.keys(values).join('|') + "\b", 'g')
return inputStr.replace(regex, (m) => values[m] )
}
console.log(findreplace('aBc'))
console.log(findreplace('AbC'))
console.log(findreplace('ABC'))
只需在 Object.entries(values)
的帮助下遍历 values
:
function findreplace(inputStr) {
const values = {
"a": "A",
"B": "x",
"c": "C"
};
for (const [search, replace] of Object.entries(values)) {
inputStr = inputStr.replace(search, replace);
}
return inputStr;
}
console.log(findreplace("abc"));
我需要 JavaScript 中的一个函数,它以一个字符串作为输入,用相应的值替换许多子字符串,然后 returns 结果。例如:
function findreplace(inputStr) {
const values = {"a": "A",
"B": "x",
"c": "C"};
// In this example, if inputStr is "abc", then outputStr should be "AbC".
return outputStr
}
我知道如何单独查找和替换,但我想知道是否有一种简单的方法可以同时处理多对(区分大小写的)值。
谢谢!
您可以join keys
构建正则表达式,然后replace
相应地
function findreplace(inputStr) {
let values = { "a": "A", "B": "x", "c": "C" };
let regex = new RegExp("\b" + Object.keys(values).join('|') + "\b", 'g')
return inputStr.replace(regex, (m) => values[m] )
}
console.log(findreplace('aBc'))
console.log(findreplace('AbC'))
console.log(findreplace('ABC'))
只需在 Object.entries(values)
的帮助下遍历 values
:
function findreplace(inputStr) {
const values = {
"a": "A",
"B": "x",
"c": "C"
};
for (const [search, replace] of Object.entries(values)) {
inputStr = inputStr.replace(search, replace);
}
return inputStr;
}
console.log(findreplace("abc"));