dork dork - 2 months ago 6
Javascript Question

Matching multiple instances of pattern in string

I'm trying to save helper strings (kind of like Stack's

[enter link description here][1]
) to the database and compile them as HTML when retrieved/viewed. A sample text is:

var str = 'This is just a sample text followed by an {{image: imageUrl1}}. And here is another {{image: imageUrl2}}.';


I tried the following RegEx:

str.match(`/(\{\{image:)[^(.*\}\})]*.*(\}\})/g`);


But I just get
["{{image: imageUrl1}}. And here is another {{image: imageUrl2}}"]
.

What should be the RegEx pattern so that the result is
["{{image: imageUrl1}}", "{{image: imageUrl2}}"]
?

Answer

The regex is greedy(matches all possible results to satisfy the condition). That means, the regex will match the string from {{ to the last }}. To match only until the first }} symbols, make it lazy by adding ? quantifier after the * quantifier.

/{{image:[^}]*?}}/g

Here's live demo on RegEx101

Explanation:

  1. {{image:: Match {{image: literal
  2. [^}]*?: Match anything but } lazily
  3. }}: Match }} literals

Note that surrounding the regex by back-ticks makes it string. Use the regex literal syntax.

var str = 'This is just a sample text followed by an {{image: imageUrl1}}. And here is another {{image: imageUrl2}}.';

var matches = str.match(/{{image:[^}]*?}}/g);
console.log(matches);


To extract the URL, use the capturing group and get the first captured group.

/{{image:\s*([^}]*?)}}/

var str = 'This is just a sample text followed by an {{image: http://someURLHERE.domain}}. And here is another {{image: imageUrl2}}.';

var regex = /{{image:\s*([^}]*?)}}/g;
var match = '';
var urls = [];

while (match = regex.exec(str)) {
    urls.push(match[1]);
}

console.log(urls);