kamilws
kamilws

Reputation: 171

Javascript find and replace src variables

imagine we have a variable in javascript

var html = "<html>...<img src="a"></img>...<a><img src="b"></img></a></html>"

we never know when img tag are located. We don't have any id's. They only have different src, and we know this src because we have them stored in a database.

How to write a method that will take every html content from 'html' variable defined above and change only src's there. For example if I know that src has a value 'a' then I want to invoke some method that will write there 'c' instead of an 'a' and so on . With some loop I would like to change src's only.

Any thoughts?

Upvotes: 0

Views: 1640

Answers (2)

Munawir
Munawir

Reputation: 3356

From your question, you know the current src.

we know this src because we have them stored in a database

with curSources storing current src's and having new src's in newSources array, you can loop through the string to replace the src of every img tag

var html = '<html>...<img class="someclass" src="a"></img>...<a><img src="b"></img></a></html>';
var count = (html.match(/<img/g) || []).length;  //number of img tags

var curSources = ['a','b'];
var newSources = ['c','d'];

for (i=1; i<=count; i++) {
  a = html.split('<img', i).join('<img').length;  //index of i'th occurance of <img
  b = html.indexOf('src',a);                      //index of i'th occurance of src
  c = html.substring(a,b+5);                      //split from <img to src="
  html = html.replace(c+curSources[i-1]+'"',c+newSources[i-1]+'"');
}

alert(html);

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337700

Once you put that string in a jQuery object you can use standard DOM traversal methods on it. Try this:

var html = '<html>...<img src="a"></img>...<a><img src="b"></img></a></html>';
$(html).find('img[src="a"]').prop('src', 'c');

Thanks to @Tushar for pointing out that you need to also be careful with the quotes you use in the HTML string. If you use " within the string you should use ' to delimit it, as in the example above.

Upvotes: 1

Related Questions