regex replace urls with anchors ONLY if not already in anchors

后端 未结 3 1357
予麋鹿
予麋鹿 2021-01-21 22:54

I\'ve seen similar questions asked before, but none with a working solution.

I am trying to replace all urls on a page with anchor tags, but only those which aren\'t alr

3条回答
  •  心在旅途
    2021-01-21 23:02

    If you are doing it on the client-side it might be worth doing it by walking document tree

    Look through text nodes (nodeName="#text") and if there is substring starting with http/https and parent tag is not A - replace it with pattern (\1 etc)

    consider this to start

     // getting all tags where there is a text with 'http' which are not links
     var textTags = [].slice.call(document.getElementsByTagName('*'))
            .filter(function(n) { 
                   return !n.children.length 
                      && n.nodeName !='A' && n.nodeName !='INPUT' 
                      && (n.innerHTML.indexOf('http') > -1) })
    
     for(var i in textTags) {
       // your code to replace links with whatever you want
     }
    

提交回复
热议问题