使用正则表达式替换字符串中的所有图像标签
Replacing all image tags in a string using regular expression
我想替换 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, "</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, "</amp-img>");
let final = result.replace(/<img/g,'<amp-img');
console.log(final);
我想替换 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, "</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, "</amp-img>");
let final = result.replace(/<img/g,'<amp-img');
console.log(final);