我有类似的东西
var string = "<h1>Hi {{name|there}}</h1>
<p>This is a message<br>
</p>
<p>Hello hello</p>"
我想找到所有 {{...}} 标签并将其替换为具有相应值的第一个属性(| 的左侧)。如果该值不存在,我想用右侧的“回退”替换标签(在本例中为字符串“there”)
到目前为止,我已经尝试过类似下面的方法,但它没有得到组
/{{(.+)|(.+)}}/
有什么想法吗?
最佳答案
你可以这样做:
var string = "<h1>Hi {{name|there}}</h1> <p>This is a message<br></p><p>Hello hello</p>";
// If the variable exists
console.log(parse(string, {name: "Tony"}));
// If the variable is not set
console.log(parse(string, {potato: "Tony"}));
function parse(str, values){
str = str.replace(/\{\{(.*)\|(.*)\}\}/g,function(arg, match1, match2){
var data = match1.split("|");
var variable = match1;
var fallback = match2;
var replace = fallback;
if(typeof(values[variable]) != "undefined"){
replace = values[variable];
}
return replace;
});
return str;
}
关于javascript - 在同一行中匹配多个模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839576/