Search code examples
javascripthtmlregex

Replace class name inside class attribute in HTML string


I have HTML string and I want to replace specific class name with another. I want do it using regular expression. I found a way, to replace all strings inside HTML string, but I want to be sure that I will replace only this one inside class="...".

I have something like this:

export const replace = () => {
  const htmlString =
  '<di class="class-to-replace">\n<div class="row">\n <p>class-to-replace</p></div>\n</di>';

  const className = 'class-to-replace';
  const classReplacement = 'new-class';
  const regex = new RegExp('\\b' + className + '\\b', 'g');

  return htmlString.replace(regex, classReplacement);
};

And it works, however it replaces all the occurrences. How can I scope it only to class attribute so that changing the class name does not also affect the change of content?


Solution

  • Here's how to use DOMparser to do this correctly

    const replace = (html, search, replace) => {
        const doc = new DOMParser().parseFromString(html, "text/html");
        doc.querySelectorAll(`.${search}`).forEach(el => el.classList.replace(search, replace));
        return doc.body.innerHTML;
    };
    
    const htmlString = '<di class="class-to-replace">\n<div class="row">\n <p>class-to-replace</p></div>\n</di>';
    const className = 'class-to-replace';
    const classReplacement = 'new-class';
    console.log(replace(htmlString, className, classReplacement));