Micka
Micka

Reputation: 15

How to replace brackets in specific attribute in html with js?

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.

Upvotes: 1

Views: 63

Answers (1)

Ibrahim
Ibrahim

Reputation: 6088

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)

Upvotes: 1

Related Questions