Search code examples
javascriptregexhtml-parsing

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? :-)


Solution

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