Reputation: 4651
I have a variable as below
var a = "Hi this is test. <img src='http://www.test.com/img1.jpg'> Test ends here";
I want to replace the src
of image tag to some other image url lets say http://www.test2.com/img2.jpg
So the output should be
var b = "Hi this is test. <img src='http://www.test2.com/img2.jpg'> Test ends here";
Both the image path would be dynamic.
Please help.
Upvotes: 0
Views: 1512
Reputation: 26320
Look the example: http://jsfiddle.net/ricardolohmann/Ww2Lu/ You can change the src just passing the new one thrue the param.
Upvotes: 0
Reputation: 13134
See this example: http://jsfiddle.net/pnwKs/
Depending on how you want to change the url, you can use the attr command.
// changes the full SRC path
$('#1').attr('src', 'http://placehold.it/350x250');
// replaces some part of the SRC path
$('#2').attr('src', $('#1').attr('src').replace('250','400'));
If it's inside a string you could do:
var a = "Hi this is test. <img src='http://www.test.com/img1.jpg'> Test ends here";
a.replace('img1.jpg', 'img2.jpg');
Upvotes: 0
Reputation: 20180
You can set the url of the image by making it a jquery object, like so:
var $myImg = $("<img src='http://www.test.com/img1.jpg'>");
$myImg.attr("src","http://www.test2.com/img2.jpg");
Upvotes: 6