0

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}}"]?

Tushar
  • 85,780
  • 21
  • 159
  • 179
dork
  • 4,396
  • 2
  • 28
  • 56

1 Answers1

1

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);
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • what does `greedy` mean? – dork Oct 07 '16 at 03:04
  • @dork Please see [What do lazy and greedy mean in the context of regular expressions?](http://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions) – Tushar Oct 07 '16 at 03:08