Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ignore specific value inside html attribute by Regexp

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading