Match text not inside span tags

后端 未结 1 1268
日久生厌
日久生厌 2021-01-01 05:50

Using Javascript, I\'m trying to wrap span tags around certain text on the page, but I don\'t want to wrap tags around text already inside a set of span tags.

Curren

相关标签:
1条回答
  • 2021-01-01 06:45

    First off, you should know that parsing html with regex is generally considered to be a bad idea—a Dom parser is usually recommended. With this disclaimer, I will show you a simple regex solution.

    This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."

    We can solve it with a beautifully-simple regex:

    <span.*?<\/span>|(\bapples\b)
    

    The left side of the alternation | matches complete <span... /span> tags. We will ignore these matches. The right side matches and captures apples to Group 1, and we know they are the right ones because they were not matched by the expression on the left.

    This program shows how to use the regex (see the results in the right pane of the online demo). Please note that in the demo I replaced with [span] instead of <span> so that the result would show in the browser (which interprets the html):

    var subject = 'Red apples are my <span class="highlight">favourite apples.</span>';
    var regex = /<span.*?<\/span>|(\bapples\b)/g;
    replaced = subject.replace(regex, function(m, group1) {
        if (group1 == "" ) return m;
        else return "<span class=\"highlight\">" + group1 + "</span>";
    });
    document.write("<br>*** Replacements ***<br>");
    document.write(replaced);
    

    Reference

    • How to match (or replace) a pattern except in situations s1, s2, s3...
    • Article about matching a pattern unless...
    0 讨论(0)
提交回复
热议问题