2

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">.

1 Answer 1

2

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");
Sign up to request clarification or add additional context in comments.

5 Comments

And what if the regular expression for numbers is this: var rxp = new RegExp("(([0-9]+\.?[0-9]+)|([0-9]+))", "gm");
I do not see any problems since you are only matching digits and an optional dot between the numbers: var rxp = new RegExp("[0-9]+(?:\\.[0-9]+)?(?![^>]*>\"thgil\"=ssalc\\s+naps<)", "gm");. EDIT: I removed \b word boundary, perhaps, you also need to remove digits even in case of xxx123.
This is a really creative solution
@stribizhev I have a little problem that if class of span is not light, I mean if it will something that I don't know then what will be the regular expression?
@EMM: @EMM: It will be even easier: var rxp = new RegExp("[0-9]+(?:\\.[0-9]+)?(?![^>]*>[^<]*\\bnaps<)", "gm");. Sample code here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.