Search code examples
javascriptregexamp-htmlreplaceall

Replacing all image tags in a string using regular expression


I want to replace all image tags in an HTML string. I wrote the below code. However it only replaces the first instance of it. How can I replace all?I tried replaceAll() method, it is not working in 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);

Solution

  • The g modifier is used to perform a global match (find all matches rather than stopping after the first match). See this link for further info.

    Working code below:

    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);