简体   繁体   English

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

[英]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 我想将图片标签的src替换为其他图片网址,例如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: 您可以通过将图像设为jQuery对象来设置图像的url,如下所示:

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/ 参见以下示例: http : //jsfiddle.net/pnwKs/

Depending on how you want to change the url, you can use the attr command. 根据您要更改URL的方式,可以使用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'));

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传递给参数即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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