'Add new tag to the middle of element
I am trying to surround specific words in textContent with HTML tags, this could hypothetically be done by doing element.textContent = element.textContent.replaceAll("word", "<h1>word<h1>"); but that isn't parsed, and element.innerHTML= element.innerHTML.replaceAll("word", "<h1>word<h1>"); doesn't work because there is a risk that the word could be the name of a tag. Is there any solution besides writing a custom replace function that detects when in a tag?
Solution 1:[1]
You can make sure that the word you're trying to pad is not inside a tag. To do this, you need to check its surrounding characters. As long as they aren't enclosed by < and > on both sides (or make sure they are enclosed by <some tag> on the left and </?some tag> on the right like what I did below), they should be the only one to be replaced. Try this regex sample below:
function padTags(content, openTag, word, closeTag) {
console.log(content)
const replacement = openTag + word + closeTag;
const regex = `(?<!<[^<>]*)${word}(?![^<>]*>)`;
const pattern = new RegExp(regex, 'g');
return content.replace(pattern, replacement);
}
console.log(padTags(`<p class="questions">What's your favorite class?</p>`,
'<custom-tag>', 'class', '</custom-tag>'));
console.log(padTags(`<div><p class="test">class</p></div>`,
'<custom-tag>', 'class', '</custom-tag>'));
console.log(padTags(`<div> class <p data-customvar="<class>">This is my class </p>class</div>`,
'<custom-tag>', 'class', '</custom-tag>'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
