[英]Replace a part of string using jQuery/JavaScript
我有一個變量如下
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";
這兩個圖像路徑都是動態的。
請幫忙。
您可以通過將圖像設為jQuery對象來設置圖像的url,如下所示:
var $myImg = $("<img src='http://www.test.com/img1.jpg'>");
$myImg.attr("src","http://www.test2.com/img2.jpg");
參見以下示例: http : //jsfiddle.net/pnwKs/
根據您要更改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'));
如果在字符串中,則可以執行以下操作:
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.