Javascript 如何在js中执行循环替换
我有一根这样的绳子Javascript 如何在js中执行循环替换,javascript,angularjs,node.js,replace,Javascript,Angularjs,Node.js,Replace,我有一根这样的绳子 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.repl
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>');
}
var字符串=“”;
var-dom=new-JSDOM(字符串,{includeNodeLocations:true});
dom=dom.window.document.querySelectorAll(“img”);
for(var i=0;i
但我的输出是
<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个IMAG。我想这是因为异步。有人可以帮助我吗。谢谢。如果在循环中运行
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>'
});
text=string.replace(/'
});
它不需要循环 如果在循环中运行
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>'
});
text=string.replace(/'
});
它不需要循环
text
在我看来是undefined
…如果不将regex设置为全局,这可能会起作用。但是这样做还是有点奇怪。@Rayon,我编辑了我的代码。@Cerburs,你能建议一个更好的方法吗。text
对我来说出现了未定义的。如果你不将regex设置为全局的,这可能会起作用。但是这样做还是有点奇怪。@Rayon,我编辑了我的代码。@Cerburs,你能建议一个更好的方法吗。它说DOM是未定义的。我不知道函数JSDOM
的返回;在运行replace之前,您尝试console.logdom
,看它是否正确?它说dom未定义。我不知道函数JSDOM
的返回;在运行replace之前,您尝试console.logdom
,看看它是否正确?