skip to Main Content

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?

2

Answers


  1. 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));
    Login or Signup to reply.
  2. "… I have HTML string and I want to replace specific class name with another. I want do it using regular expression. …

    … How can I scope it only to class attribute so that changing the class name does not also affect the change of content?

    Try the following match pattern.

    (?<=class=(['"]))class-to-replace(?=1)
    
    let s = '<di class="class-to-replace">n<div class="row">n <p>class-to-replace</p></div>n</di>'
    let p = /(?<=class=(['"]))class-to-replace(?=1)/g
    s = s.replace(p, 'new-class')
    
    console.log(s)

    For dynamic values, use the following.  Be sure to escape the 1.

    let s = '<di class="class-to-replace">n<div class="row">n <p>class-to-replace</p></div>n</di>'
    let a = 'class-to-replace', b = 'new-class'
    let p = new RegExp(`(?<=class=(['"]))${a}(?=\1)`, 'g')
    s = s.replace(p, b)
    
    console.log(s)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search