提问人:AsZik 提问时间:6/7/2023 更新时间:6/9/2023 访问量:123
如何在 javascript 中使用正则表达式替换字符串
How to replace the string using regex in javascript
问:
我有以下字符串和对象,
const str = "$(role.name) is $(role) team. $(role.name) started his role as $(role)"
const obj = {
role: 'Dev',
'role.name': 'Foo',
}
const expected = "Foo is Dev team.Foo started his role as Dev"
如何使用正则表达式?
我的正则表达式 ,
const data = str.match(/\$\((.*?)\)/g)
答:
2赞
IGOR Formanyuk
6/7/2023
#1
您可以将 replace() 方法与正则表达式模式一起使用。
下面是一个示例,说明如何使用给定的字符串和对象实现所需的替换:
const str = "$(role.name) is $(role) team. $(role.name) started his role as $(role)";
const obj = {
role: 'Dev',
'role.name': 'Foo',
};
// Create a regular expression pattern to match the placeholders
const pattern = /\$\(([\w.]+)\)/g;
// Replace the placeholders with the corresponding values from the object
const result = str.replace(pattern, (match, key) => obj[key]);
console.log(result);
// Output: "Foo is Dev team. Foo started his role as Dev"
评论
0赞
001
6/7/2023
有关设置答案格式的信息,请参阅 stackoverflow.com/editing-help。
0赞
Keith
6/7/2023
嗨,IGOR,欢迎来到 Stack Overflow,对于您的第一个很棒的答案,请投我的赞成票。就像 001 指出的那样,这只是您的格式,评论易于理解等。如果你有像这样的简单 Javascript,在编辑器中使用代码片段图标,你可以将代码粘贴到这里,每个人都可以尝试运行它。这次我为你做了这件事。<>
2赞
Keith
6/7/2023
#2
对于无解决方案,既好又简单。regex
replaceAll
请注意,正如评论中指出的那样,尽管这在大多数情况下都有效,但请注意,如果 在其中一个刀路上进行替换最终会在 以后的通行证,这些也将被替换。因此,我会说 最干净的解决方案是 和 回调。 我会把这个答案留在这里,因为它对其他人来说仍然有用 看。
regex
(match, key)
const str = "$(role.name) is $(role) team. $(role.name) started his role as $(role)"
const obj = {
role: 'Dev',
'role.name': 'Foo',
}
const fillTemplate = (str, obj) => {
let ret = str;
for ([k,v] of Object.entries(obj))
ret = ret.replaceAll(`$(${k})`, v);
return ret;
}
console.log(fillTemplate(str, obj));
评论
0赞
Sebastian Simon
6/7/2023
请注意,如果 和 分隔符出现在替换的子字符串中,这将继续替换它们;结果还取决于对象的枚举顺序,而不应依赖该顺序。使用 ,结果将是 ;但是有了 ,它将是 .$(
)
const str = "$(a)c$(b)", obj = { a: "$(", b: ")", c: "x" };
"x"
const str = "$(a)c$(b)", obj = { a: "$(", c: "x", b: ")" };
"$(c)"
0赞
Keith
6/7/2023
@SebastianSimon是的,这是一个很好的观点。用 看这个例子会更好。我会对此发表评论。干杯。。regex
(match, key)
4赞
The fourth bird
6/7/2023
#3
您应该替换,而不是匹配。由于您已经有捕获组,因此您可以检查组 1 是否作为键存在于 obj 中。
请注意,在您的中,这里没有空间expected
team.Foo
const str = "$(role.name) is $(role) team. $(role.name) started his role as $(role)"
const regex = /\$\(([^()]*)\)/g;
const obj = {
role: 'Dev',
'role.name': 'Foo',
}
const result = str.replace(regex, (m, g1) => obj.hasOwnProperty(g1) ? obj[g1] : m);
console.log(result);
评论
1赞
anubhava
6/8/2023
善用hasOwnProperty
0赞
The fourth bird
6/8/2023
@anubhava 谢谢,不幸的是,它已经关闭了,你能帮忙投票重新开放它吗?我认为这是一个非常明确的问题。
1赞
anubhava
6/8/2023
是的,我会投票打开它
评论
replace
regex
replace
方法用相应的关键字替换多个关键字?、是否可以在运行时替换(或重用)ES6 模板文字?和延迟执行 ES6 模板文字。使用模板字符串,或使用带有 replace
的方法,其中包含非贪婪正则表达式和函数作为第二个参数。