0

Given a string such as

The quick brown {{ fox }} jumped over the lazy <em>{{ dog }}</em>

I'm looking for a pattern that will match all instances of {{ not preceded by the <em> block

Whilst the pattern /(?<!>)\{{2}/gm will work, this is not an option for Firefox and IE flavours of JS.

I’ve done a fair bit of digging and can find a great deal of examples that almost get there but not quite. Getting a positive match for the string _>{{_ is no problem, but it’s the reverse of this that I’m looking for.

I feel like I might be heading in the wrong direction with a lookup approach like this. Am I missing something more simple here?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75

3 Answers3

0

I'm guessing you want to access whatever is inside those {{ }} and wrap it in a <em> tag.

You can use the RegEx ([^>]){{(.*?)}}

And replace with $1<em>$2</em>

  • ([^>]) makes sure the preceding char isn't a >

  • {{(.*?)}} matches anything inside {{ }}

Demo.

Zenoo
  • 12,670
  • 4
  • 45
  • 69
  • That almost gets there - only slight snag in it is it will match the _e_ in `space{{ here }}` @Joseph Marikle's example above looks to have nailed it – petehotchkiss Jul 27 '18 at 13:58
  • @petehotchkiss It will, but it also replaces it back with `$1` – Zenoo Jul 27 '18 at 13:59
0

You may match any <em> contents using <em>[\s\S]*?<\/em> regex and then match the {{...}} substrings with {{[\s\S]*?}} pattern in all other contexts, capture either of them and use custom logic in the callback method:

console.log(
  "The quick brown {{ fox }} jumped over the lazy <em>{{ dog }}</em>"
          .replace(/<em>[\s\S]*?<\/em>|({{[\s\S]*?}})/g, function ($0,$1) {
                 return $1 ? '<em>' + $1 + '</em>' : $0;
            })
);

With $1 ?, we check if Group 1 matched, and if yes, the value is wrapped with <em> tags, else, it is just pasted back with $0 (the whole match).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

You could instead look ahead for the closing tag: /{{[^}]*?}}(?!<\/em>)/g

let test = "The quick brown {{ fox }} jumped over the lazy <em>{{ dog }}</em> asdfafds {{ fox }} asdf asdf asdf sdfasdfsdf <em>{{ dog }}</em>";
console.log("input: " + test);
console.log("output: " + test.replace(/({{[^}]*?}})(?!<\/em>)/g, "<em>$1</em>"));
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129