Tarlen
Tarlen

Reputation: 3797

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?

Upvotes: 1

Views: 143

Answers (4)

Redu
Redu

Reputation: 26191

You might do as follows;

var str = "<h1>Hi {{name|there}}</h1>",
   val1 = "muçaços",
   val2 = undefined,
   str1 = str.replace(/\{\{(\w+)\|(\w+)\}\}/,(m,p1,p2) => val1||p2),
   str2 = str.replace(/\{\{(\w+)\|(\w+)\}\}/,(m,p1,p2) => val2||p2);
console.log(str1);
console.log(str2);

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627410

If your input can look like {{name|there}} (=> name), or {{|there}} (=> there) or {{there}} (=> there), you may use the following approach:

var string = `<h1>Hi {{name|there}}</h1>
<p>This is a {{|message}}<br>
</p>
<p>Hello {{hello}}</p>`;
var rx = /{{(.*?)(?:\|(.*?))?}}/g;
console.log(string.replace(rx, function(m,g1,g2) {
  return g1 ? g1 : g2;
}));

Details:

  • {{ - literal {{ text
  • (.*?) - Group 1 capturing any 0+ chars other than linebreak symbols as few as possible up to the first
  • (?:\|(.*?))? - optional sequence of
    • \| - literal |
    • (.*?) - Group 2 capturing any 0+ chars other than linebreak symbols as few as possible up to the first
  • }} - literal }} text.

In the replacement, Group 1 is checked first, and if it is not empty its contents are returned. Else, Group 2 contents are returned.

Upvotes: 1

antoineMoPa
antoineMoPa

Reputation: 1024

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

Upvotes: 1

Zergatul
Zergatul

Reputation: 2018

You should escape all these characters: { } |

string.match(/\{\{(.+)\|(.+)\}\}/)

Upvotes: 0

Related Questions