I am looking for a regex to skip data-value="4" attribute from string for example I have a string i.e
Hello this is string <sfpart contenteditable="false" data-value="4">‏</sfpart> and the 4 number in string
Now in the above string I want to replace 4 with lets say <span class="yellow">4</span> but not 4 inside the data-value="4"
I can grab 4 and replace it with the <span class="yellow">4</span> by doing below code
const reg = new RegExp('('4')', 'gi');
const str = str.replaceAll(reg, '<span class="yellow">$1</span>');
But the issue is above regex picking 4 inside data-value attribe and replacing it with the html span tags i.e data-value="<span class="yellow">4</span>" so I want skip that part.
Any genuis to help?
Use assertions. In this case a negative lookbehind:
(?<!data-value=")\d+
This will ensure you match only the character 4 that is not immediately preceded by the data-value attribute name (as well as the =" that prefixes the attribute value).
Try it out here: https://regex101.com/r/SzPUOx/1
You shouldn't be using regex to match HTML tags and attributes. Use DOMParser to parse your string instead, and then iterate through all the nodeChildren and perform the replacement in text nodes (which will have a nodeType of 3):
const string = 'Hello this is string <sfpart contenteditable="false" data-value="4">‏</sfpart> and the 4 number in string';
const parser = new DOMParser();
const parsedNode = parser.parseFromString(string, "text/html").body;
for (let i = 0; i < parsedNode.childNodes.length; i++) {
const node = parsedNode.childNodes[i];
if (node.nodeType === 3) {
const replacementNode = document.createElement('span');
replacementNode.innerHTML = node.textContent.replaceAll(/(\d+?)/gi, '<span class="yellow">$1</span>');
node.parentNode.insertBefore(replacementNode, node);
node.parentNode.removeChild(node);
}
}
console.log(`Input:\n${string}`);
console.log(`Output:\n${parsedNode.innerHTML}`);
document.querySelector('#input').innerHTML = string;
document.querySelector('#output').innerHTML = parsedNode.innerHTML;
#input,
#output {
border: 1px solid #000;
padding: 8px;
margin: 8px;
}
span.yellow {
background-color: yellow;
}
<strong>Input:</strong>
<div id="input"></div>
<strong>Output:</strong>
<div id="output"></div>