CdB
CdB

Reputation: 4908

javascript regex - replace each match of given expression with different string

I have a string contaning some html markup, like this:

var html = "<div>
    <img src="http://test.com/image1.png" />
    <h1>SOME TEXT</h1>
    <img src="http://text.com/image2.jpg" />
</div>";

i want to replace all urls inside src="..."

It is ok if i do html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, "SOME_URL");
then all src="..." become src="SOME_URL"

But now i want to replace each match with a different string, taken from an array, but i'm having trouble with this.
I think i have to use a function for the replacement, but not sure how to implement it.
Something like:
html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, function ($0, $1){ //what do i do here??? });

So, if i have:

var arr = [];
arr['http://test.com/image1.jpg']='file1';
arr['http://test.com/test.jpg']='file3';

the html string from above will become:

"<div>
    <img src="file1" />
    <h1>SOME TEXT</h1>
    <img src="http://text.com/image2.jpg" />
</div>"

Note that 'http://text.com/image2.jpg' is not a key of the array, so it does not gets replaced.

Any help appreciated, thank you in advance.

Upvotes: 0

Views: 620

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

I'd forget about regex in this case, if you have an array containing all urls and their individual replacements in an object, why not do something like:

for (i in replaceObj)
{
    html = html.split(i).join(replaceObj[i]);
}

tried it in console:

html = '<div><img src="imgs/img.jpg"/></div>';
replaceObj = {};
replaceObj['imgs/img.jpg'] = 'file';
for(i in test){html = html.split(i).join(replaceObj[i])};

output: <div><img src="file"/></div>. You could split on src="'+i'"' and concat. the same when joining to be on the safe side... but bottom line: keep it simple, whenever you can

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

var html = '<div><img src="http://test.com/image1.jpg" />...</div>';

var arr = { 
 'http://test.com/image1.jpg' : 'file1',
 'http://test.com/test.jpg'   : 'file3'
}

html = html.replace(/[^-]src\=["|'](.*?)['|"]/g, function ($0, $1){ 
  return ' src="' + (arr[$1] || $1) + '"';
});

console.log(html) returns

"<div><img src="file1" /><h1>SOME TEXT</h1><img src="http://text.com/image2.jpg" /></div>"

Upvotes: 1

Related Questions