nexana
nexana

Reputation: 1166

Javascript Regex: exclude result if preceded by href="

I'm struggling to get a string replaced in Javascript by a regex matching pattern. I want to replace all matches of {{$myparam}} to be surrounded by a span tag. This works (see code below). But I want to prevent replacements when a match is preceded by href=".

Example: href="{{$myparam}} must NOT be replaced. {{$myparam}} MUST be replaced. myparam can be any text string.

  var highlighted = html.replace(/(\{\{(.*?)\}\})/g, function highlight(x) {
       return "<span class='highlight'>" + x + "</span>";
   });

I've checked out numerous examples in other threads, but I cannot find a solution that works for my case.

Upvotes: 1

Views: 459

Answers (2)

Jeremy Jones
Jeremy Jones

Reputation: 5631

This seems a bit simpler, just make the href part optional:

mystring = 'this has {{$param1}} and {{$param2}} and href="{{$param3}}" too';

console.log(mystring
 .replace(/(href=.)?\{\{([^{} ]+)\}\}/g, 
          function (match,chk,param) {
             return "undefined" !== typeof(chk)
                    ? match
                    : '<span class="highlight">' + param + '</span>';
          }));

The second argument to the callback function is the 'check' part, and the third argument is the captured parameter name. Since the check part is optional and it's fairly precise, it'll only be defined at all if it's 'href="'.

Output, with newlines added for readability:

this has <span class="highlight">$param1</span> 
and <span class="highlight">$param2</span> 
and href="{{$param3}}" too

Upvotes: 0

Jan
Jan

Reputation: 43169

You could use

var subject = 'href="{{$myparam}}" or any other {{$myparam}}';
var regex = /"[^"]*"|(\{\{(.*?)\}\})/g;

replaced = subject.replace(regex, function(m, group1) {
    if (typeof group1 == 'undefined') return m;
    else return "<span class='highlight'>" + group1 + "</span>";
});
alert(replaced);
# href="{{$myparam}}" or any other <span class='highlight'>{{$myparam}}</span>

See a demo on regex101.com.


The idea here is to check for

not_interesting|not_interesting_either|(very_interesting)

and check for the presence of a captured group. You can put anything not interesting to the left as in this example: "[^"]*" (that is anything between double quotes).
If you want to read more on the subject, have a look here.

Upvotes: 1

Related Questions