【问题标题】:How to perform replace in a loop in js如何在js中循环执行替换
【发布时间】:2017-12-19 03:37:25
【问题描述】:

我有一个这样的字符串

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 个图像。我认为这是因为异步。谁能帮助我。谢谢。

【问题讨论】:

  • text 在我面前出现undefined...
  • 如果您不将正则表达式设为全局,这可能会起作用。但是这样做仍然有点奇怪。
  • @Rayon,我编辑了我的代码。
  • @Cerbrus,你能建议更好的方法吗?

标签: javascript angularjs node.js replace


【解决方案1】:

好吧,如果你在循环中运行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>'
});

而且它不需要循环;

【讨论】:

  • 它说 DOM 未定义。
  • 不知道函数JSDOM的返回;您尝试在运行替换之前 console.log dom ,看看它是对的吗?
猜你喜欢
  • 2018-09-10
  • 2017-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-18
  • 2016-07-11
相关资源
最近更新 更多