regex 如何在JavaScript中使用正则表达式替换字符串

tzxcd3kk  于 2023-06-25  发布在  Java
关注(0)|答案(4)|浏览(137)

我有下面的字符串和对象,

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"

如何使用regex?
我的正则表达式

const data = str.match(/\$\((.*?)\)/g)
qyyhg6bp

qyyhg6bp1#

而不是匹配,你应该替换。因为已经有了捕获组,所以可以检查组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);
yvfmudvl

yvfmudvl2#

可以将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"
weylhg0b

weylhg0b3#

对于一个没有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));
ippsafx7

ippsafx74#

要在JavaScript中使用正则表达式替换字符串,可以使用replace()方法和正则表达式模式。下面是如何使用给定的字符串和对象实现预期结果:

const str = "$(role.name) is $(role) team. $(role.name) started his role as $(role)";
const obj = {
  role: 'Dev',
  'role.name': 'Foo',
};

const expected = str.replace(/\$\((.*?)\)/g, (match, group) => {
  const property = group.replace(/\./g, '\\.');
  return obj[property];
});

console.log(expected);

说明:

  • 正则表达式模式/\$\((.*?)\)/g匹配任何以$(开始并以)结束的子字符串。.*?非贪婪地捕获内部内容。
  • replace()方法用回调函数替换每个匹配的子字符串。
  • 在回调函数中,match参数表示匹配的子串,group参数表示捕获的内部内容。
  • group用于使用方括号表示法访问obj对象中的相应属性。
  • replace()方法返回修改后的字符串以及所做的替换。

得到的expected值为:"Foo是Dev团队。Foo开始扮演Dev"。

相关问题