简体   繁体   中英

How can I replace a keyword but in HTML tags by JavaScript regular expression?

Here's some codes:

<p id="para">
    This is my webpage:
    <a href="http://example.com">
        http://example.com
    </a>
    http://example.com
</p>

<script type="text/javascript">
    var para = document.getElementById('para').innerHTML;
    var re = new RegExp(/(http:\/\/example\.com)/, 'gi'); // Should be fixed

    para = para.replace(re, '<strong>$1</strong>');

    // Result HTML code will be something like below:
    //
    // <p id="para">
    //     This is my webpage:
    //     <a href="&lt;strong&gt;http://example.com&lt;/strong&gt;">
    //         <strong>http://example.com</strong>
    //     </a>
    //     <strong>http://example.com</strong>
    // </p>
    //
    // So, I don't want to change the tag attribute,
    // and want to write regexp to avoid this problem.
</script>

Hopegully, this make sense. Thanks in advance.

UPDATE

I'm sorry I've changed the code a bit. Added addtional http://example.com under the a tag. I'd also like to put <strong> tag here but a 's attribute.

/<a.+?>(.+)</a>/ is the regex you're looking for. With gi as flags.

EDIT in response to the question update:

var para = document.getElementById('foo');
para.innerHTML = ( para.innerHTML.replace(/[^"'](http:\/\/.+?)\s/gi, '<strong>$1</strong>'));

Simplest way is to probably use 2 regexs one for the HTML encoded version and another for the non-encoded version.

The first one would be /(http:\\/\\/example.com)/

The second one would be /http:\\/\\/example.com(?=")/. This one uses a lookahead. It assumes you have " at the end of the URL. You could also try a lookbehind but from what I recall support lookbehind is not always supported Javascript. So lookahead might be the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM