使用正则表达式替换字符串中的所有图像标签

问题描述

我想替换HTML字符串中的所有图像标签。我写了下面的代码。但是,它仅替换它的第一个实例。我该如何替换全部?我尝试了replaceAll()方法,该方法在chrome中不起作用。

let content = "Hello <img src='abc.png' alt='AMP Example' height='200'width='300' >. Learn more";
let result = content.replace(/(<img[^>]+>(?:<\/img>)?)/i,"$1</amp-img>");
console.log(result);
let final = result.replace('<img','<amp-img');
console.log(final);

解决方法

g修饰符用于执行全局匹配(查找所有匹配项,而不是在第一个匹配项后停止)。有关更多信息,请参见this link

下面的工作代码:

let content = "Hello <img src='1stImage.png' alt='AMP Example' height='200'width='300' >Learn more <img src='2ndImage.png' alt='AMP Example' height='200'width='300' >";
let result = content.replace(/(<img[^>]+>(?:<\/img>)?)/g,"$1</amp-img>");

let final = result.replace(/<img/g,'<amp-img');
console.log(final);