1

I have this html code :

<div>
    <a href="TOTO/{{CODE}}/TOTO/{{CLICK}}/{{OPEN}}" data-href="TOTO/{{CODE}}/TOTO/{{CLICK}}/{{OPEN}}">FOO1</a>
</div>
<div>
    <a href="{{CODE}}/{{CLICK}}/BAR" data-href="{{CODE}}/{{CLICK}}/BAR">FOO2</a>
</div>

and i would like to change {{CODE}} by %%CODE%% and {{CLICK}} by %%CLICK%% and {{OPEN}} by %%OPEN%%, but only in the attributes data-href in all of div.

I do not know how to target only data-href. I tried this to target brackets in data-href attribute :

/data-href="([^"]+)({{([^\"]*)}}+)([^"]+)"/g

But it doesn't work !

Thanks for your help.

1 Answer 1

1

You could use a simple regex to match whatever inside data-href. A simple regex can be something like this

data-href=".*?"

Then, you can replace all matches with one loop

var str = '<div><a href="TOTO/{{CODE}}/TOTO/{{CLICK}}/{{OPEN}}" data-href="TOTO/{{CODE}}/TOTO/{{CLICK}}/{{OPEN}}">FOO1</a></div><div><a href="{{CODE}}/{{CLICK}}/BAR" data-href="{{CODE}}/{{CLICK}}/BAR">FOO2</a></div>';
var myRegexp = /data-href=".*?"/g;
var match = myRegexp.exec(str);
while (match != null) {
  str = str.replace(match[0], match[0].replace(/{{|}}/g, '%%'));
  match = myRegexp.exec(str);
}
console.log(str)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.