我有一串看起来像这样的句子
Hey {someone}, How are you?
或
Hey {someone}, Do you want to go out for lunch?
[问题] 现在,我想将上下文中的{someone}替换为一个人的名字,假设具有该人的名字的变量是var personName。
我该如何实现?
答案 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);