简体   繁体   中英

Replace a part of string using jQuery/JavaScript

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.

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");

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');

看一下示例: http : //jsfiddle.net/ricardolohmann/Ww2Lu/您可以更改src,而只需将新的src传递给参数即可。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM