Reputation: 181
I have the following code:
document.getElementById("rep").innerHTML = document.getElementById("rep").innerHTML.replace(rxp, "abc");
<div id="rep"> asd 123 asd <span class="light">123</span> asd 123 asd <span class="light">123</span> </div>
Here, rxp
is a regular expression which matches the numbers.
Problem is that I want to replace only those 123
that are not enclosed in span
and not to replace 123
which enclosed in <span class="light">
.
Upvotes: 2
Views: 84
Reputation: 626748
You can use the reverse string trick to leverage a negative look-ahead instead of a negative look-behind (that is not supported by the JavaScript regex engine):
function revStr(str) {
return str.split('').reverse().join('');
}
var rxp = new RegExp("[0-9]+(?:\\.[0-9]+)?(?![^>]*>\"thgil\"=ssalc\\s+naps<)", "gm");
var str = '<div id="rep"> asd 123 asd <span class="light">123</span> asd 123 asd <span class="light">123</span> </div>';
var result = revStr(revStr(str).replace(rxp, revStr('abc')));
document.getElementById("res").value = result;
<input id="res"/>
You should also use a reversed replacement string.
EDIT: In case you need to check if the number is not enclosed in any <span>
tag with any attributes, you can use a simpler regex:
var rxp = new RegExp("[0-9]+(?:\\.[0-9]+)?(?![^>]*>[^>]*\\bnaps<)", "gm");
Upvotes: 2