Betty St
Betty St

Reputation: 2861

Match Regex if not inside specific HTML tag

I would like to get special formatted strings ({string}) out of the HTML which are not inside a specific HTML tag.

For example I would like to match {test} and not <var>{test}</var>.

Therefore I am using the following regex: (excluding is done with ?!)

(?!<var>)\{\S+?\}(?!<\/var>)

So this works very well for texts with spaces, but if I have something like (where there is no space in-between):

<var>{name}</var>{username} 

it matches two {}-strings: {name}</var>{username}

How can I just match {username} here?

Update: If I need to do something like this

<var.*?<\/var>|(\{\S+?\})

How can I get the matched values, because the matched index depends on the position.

Examples:

Match 1:

"{username}<var>{name}</var>".match(/<var.*?<\/var>|(\{\S+?\})/g);
=> ["{username}", "<var>{name}</var>"]

Match 2:

"<var>{name}</var>{username}".match(/<var.*?<\/var>|(\{\S+?\})/g);
=> ["<var>{name}</var>", "{username}"]

Current Solution:

angular.forEach(html.match(regex), function (match) {
  if(match.substring(0, 4) !== '<var') {
    newAdded = match;
  }
});

Is this really the 'best' solution for JavaScript?

Upvotes: 1

Views: 1946

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

Here is how you can achieve this using the following regex:

/<var.*?<\/var>|(\{\S+?\})/g;

var s = '<var>{name}</var>{username}<var>{newname}</var>{another_username}';
var log = [];
var m;
var regex = /<var.*?<\/var>|(\{\S+?\})/g;
while ((m = regex.exec(s)) !== null) {
   if ( m[1] !== undefined) {
     log.push(m[1]);
   }
}
alert(log);

Upvotes: 3

Related Questions