我有一个大括号中包含格式字符的文本。
let str = "My name is {name} and age is {age}!";
我想使用对象属性更改它。
var myobj = { name: "x", age: "25" }
结果文本应为 "My name is x and age is 25!"
我可以使用正则表达式获取名称和年龄值。
let regex = /\{([^}]+)\}/g;
let matches = str.match(regex).map(x => x.replace(/[{}]/g, ""));
matches
是数组 ["name", "age"]
但是,如何使用正则表达式替换为对象属性?可能是很短的路吗?
您可以使用.replace
method并使用myobj
当前正则表达式从已经捕获到组1中的键中获取值:
let str = "My name is {name} and age is {age} {x}! {missing from myobj}";
var myobj = { name: "x", age: "25", x: ""}
let regex = /{([^{}]+)}/g;
console.log( str.replace(regex, (x,y) => myobj[y] !== undefined ? myobj[y] : x) );
// or a bit more modern variation
console.log( str.replace(regex, (x,y) => myobj[y] ?? x) );
如果存在捕获的键(myobj[y] ??
),则将返回相应的值。如果在中没有找到带有正则表达式的键myobj
,则将返回整个匹配项(x
)。如果找不到键,则需要返回不带花括号的值,请使用y
代替x
此处。
无需转义{
或}
出现在模式中,因为它们不能被解析为限制量词(在这种情况下,JavaScript RegExp引擎会进行一些“智能”解析)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句