使用正则表达式替换字符串中的单词

时间:2018-06-29 08:29:14

标签: javascript regex

我有一串看起来像这样的句子

Hey {someone}, How are you? 

Hey {someone}, Do you want to go out for lunch?

[问题] 现在,我想将上下文中的{someone}替换为一个人的名字,假设具有该人的名字的变量是var personName。

我该如何实现?

2 个答案:

答案 0 :(得分:1)

您可以简单地将.replace()用作str.replace('{someone}',name)。如果字符串中有多个{someone},请使用str.replace(/{someone}/g,name)之类的全局替换:

var str = 'Hey {someone}, How are you?';
var name = 'Jack';
var res = str.replace('{someone}',name);
console.log(res);

str = 'Hey {someone}, Do you want to go out for lunch?';
res = str.replace('{someone}',name);
console.log(res);

答案 1 :(得分:1)

使用正则表达式和.replace(),您可以简单地使用:


const regex   = /\{someone\}/gm;
const someone = 'Jack';
let str       = 'Hey {someone}, Do you want to go out for lunch?';

str = str.replace(regex, someone);

console.log(str);