[英]How to perform replace in a loop in js
我有這樣的字符串
var string = '<img src="test.jpg'><img src="test2.jpg>';
var dom = new JSDOM(string,{ includeNodeLocations: true });
dom = dom.window.document.querySelectorAll("img");
for(var i = 0;i< dom.length;i++) {
text = string.replace(/<img[^>]*>/g,'<amp-img layout="responsive" class="ampimageheight" src="'+dom[i].getAttribute('src')+'" width="200" height= "100"></amp-img>');
}
但是我的輸出是
<amp-img layout="responsive" class="ampimageheight" src="test2.jpg" width="200" height= "100"></amp-img><amp-img layout="responsive" class="ampimageheight" src="test2.jpg" width="200" height= "100"></amp-img>
其中只有第二個圖像src替換為2個imags。我認為這是由於異步的緣故,有人可以幫我嗎,謝謝。
好吧,如果您在循環中運行replace
,則無需設置正則表達式的標志。 因為那會在第一次循環時替換所有img
。 在第一個循環之后什么也不做。 因此,您可以刪除Regex標志,或使用回調替換函數的第二個參數,如下所示。
text = string.replace(/<img[^>]*>/g, function(str, index){
return '<amp-img layout="responsive" class="ampimageheight" src="'+dom[index].getAttribute('src')+'" width="200" height= "100"></amp-img>'
});
而且它不需要循環;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.