使用jQuery / JavaScript替换字符串的一部分

时间:2012-04-11 11:13:22

标签: javascript jquery

我有一个变量如下

var a = "Hi this is test. <img src='http://www.test.com/img1.jpg'> Test ends here";

我想将src图片代码替换为其他图片网址,让我们说http://www.test2.com/img2.jpg

所以输出应该是

var b = "Hi this is test. <img src='http://www.test2.com/img2.jpg'> Test ends here";

图像路径都是动态的。

请帮忙。

3 个答案:

答案 0 :(得分:6)

您可以通过将图像设为jquery对象来设置图像的URL,如下所示:

var $myImg = $("<img src='http://www.test.com/img1.jpg'>");
$myImg.attr("src","http://www.test2.com/img2.jpg");

答案 1 :(得分:0)

请参阅此示例:http://jsfiddle.net/pnwKs/

根据您想要更改网址的方式,您可以使用attr命令。

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

如果它在字符串中你可以做:

var a = "Hi this is test. <img src='http://www.test.com/img1.jpg'> Test ends here";
a.replace('img1.jpg', 'img2.jpg');

答案 2 :(得分:0)

查看示例:http://jsfiddle.net/ricardolohmann/Ww2Lu/ 你可以改变src只是传递新的一个param。

相关问题