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
Here’s how to use DOMparser to do this correctly
Try the following match pattern.
For dynamic values, use the following. Be sure to escape the
1
.