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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

what does greedy mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.