Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace text not within a specific-Tag in JavaScript

I have a string (partly HTML) where I want to replace the string :-) into bbcode :wink:. But this replacement should not happen within <pre>, but in any other tag (or even not within a tag).

For example, I want to replace

:-)<pre>:-)</pre><blockquote>:-)</blockquote>

to:

:wink:<pre>:-)</pre><blockquote>:wink:</blockquote>

I already tried it with the following RegEx, but it does not work (nothing gets replaced):

var s = ':-)<pre>:-)</pre><blockquote>:-)</blockquote>';
var regex = /:\-\)(?!(^<pre>).*<\/pre>)/g;
var r = s.replace(regex, ':wink:');

Can someone please help me? :-)

like image 215
acme Avatar asked Dec 19 '25 08:12

acme


1 Answers

This ought to do it:-

var src = ":-)<pre>:-)</pre><blockquote>:-)</blockquote>"

var result = src.replace(/(<pre>(?:[^<](?!\/pre))*<\/pre>)|(\:\-\))/gi, fnCallback)

function fnCallback(s)
{
    if (s == ":-)") return ":wink:"
    return s;
}

alert(result);

It works because any pre element will get picked up by the first option in the regex and once consumed means that any contained :-) can't be matched since the processor will have moved beyond it.

like image 119
AnthonyWJones Avatar answered Dec 21 '25 22:12

AnthonyWJones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!