Home > OS >  Ignore specific value inside html attribute by Regexp
Ignore specific value inside html attribute by Regexp

Time:08-01

I'm working with html templates that have variables inside. These variables are going to be replaced with some values (by regular expression). But some variables I want to exclude.

Here is my test html code:

data-coupon-patern="test {{SALE}} test"
test {{SALE}} test "
test {{SALE}} test 
data-coupon-patern="test {{SALE}} test"
data-text="test {{SALE}} test

My goal is replacing all {{SALE}} (that's how I identify variables) that is not inside data-coupon-patern attribute, using regular expression. In this attribute {{SALE}} should not be replaced.

I have tried on my own and I get this regex: /(?![^"]*"){{[\s| ]*Sale[\s| ]*}}/gi

But with this, I get replaced only last {{SALE}} in html.

I hope some wizards (someone who knows regular expression brilliant) will se this post and help me with this issue :) (if you know regexp - you are really wizard)

CodePudding user response:

You can do this by switching from a lookahead to lookbehind for the first part of your expression and updating the contents of the lookbehind expression.

Here's the updated expression:

/(?<!(data-coupon-patern="[^"]*)){{[\s|&nbsp;]*sale[\s|&nbsp;]*}}/gi

This will look for the {{sale}} pattern as long as it is not preceded by data-coupon-patern=" without a closing quote.

Output when replaced with "XXX" on the string you gave:

data-coupon-patern="test {{SALE}} test"
test XXX test "
test XXX test 
data-coupon-patern="test {{SALE}} test"
data-text="test XXX test

Note that if you're planning on running this in the browser, lookbehind is not supported in all browsers.

  • Related