Javascript Regex to replace URLs with links, but not in embed (or img) tags

后端 未结 2 440
礼貌的吻别
礼貌的吻别 2021-01-16 09:44

I\'m currently using the following code, to search the a div on a page for URLs and replace them with a tags.

However when we have a embed tags within the div it me

相关标签:
2条回答
  • 2021-01-16 10:17

    Probably, you should use DOM as recommended. But in order to make your regexp work as desired, you should prepend it with (?:^|[^"']). That means match start of line or match any character excepting ' and ". So first of your regexps will look as follows:

    /(?:^|[^"'])(ftp|http|https|file):\/\/[\S]+(\b|$)/gim  
    

    And your chaining of replace method is ugly. Code will be much more readable if you will split method invocations to different lines.

    Update: And in order to skip first excess character you can use $1 instead of $& and your regexp must be changed to this:

    /(?:^|[^"'])((ftp|http|https|file):\/\/[\S]+(\b|$))/gim  
    
    0 讨论(0)
  • 2021-01-16 10:17

    +1 to what Johannes says...

        $(document).ready(function(){
           $('div.content').contents().filter(function() {
             return this.nodeType == 3;
           }).each(function(){
                 this.nodeValue.replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,'<a href="$&" class="my_link" target="_blank">$&</a>').replace(/([^\/])(www[^ <]+(\b|$))/gim,'$1<a href="http://$2" class="my_link" target="_blank">$2</a>');
           });
        });
    

    Note the code above is untested but it should look something like that i believe.

    0 讨论(0)
提交回复
热议问题