javascript - 在同一行中匹配多个模式

标签 javascript regex

我有类似的东西

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/

相关文章:

javascript - 使用或组合两个正则表达式条件

java - 正则表达式获取两个冒号之间的值,不包括冒号

asp.net - 正则表达式在后台 url 标记中查找值

javascript - Facebook FB.Event.subscribe 不起作用

php - JQuery .ajax() 关于用户名验证

javascript - 如何对ajax请求进行速率限制?

javascript - JQUERY 使用一个对话框打开带有相应按钮的表单

Javascript 模块模式和空对象

java - 需要找到航类号的正则表达式

mysql - 从 MySQL 中的第一个整数中查找/剪切字符串