Tarlen Tarlen - 2 months ago 11
Javascript Question

Match multiple patterns in same line

I have something like

var string = "<h1>Hi {{name|there}}</h1>
<p>This is a message<br>
</p>
<p>Hello hello</p>"


I want to find all {{...}} tags and replace it with the first attribute (left-hand side of |) with a corresponding value. If that value doesn't exist, I want to replace the tag with the 'fallback' on the right-hand side (in this case the string 'there')

So far I've tried something like below, but it doesn't get the groups

/{{(.+)|(.+)}}/


Any ideas?

Answer

You could do something like that:

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;
}