Javascript make dynamic links but ignore existing links -
im using dynamically make links in webpage:
var linkword = function(obj){ for(i in obj){ var x = document.body.innerhtml; var linkstart = '<a href="'+obj[i]+'">'; var linkend = '</a>'; var reg = new regexp("\\b(" + + ")\\b","ig"); x = x.replace(reg, linkstart + + linkend); document.body.innerhtml = x; } console.log(obj); } linkword({ 'the':'http://www.example.com', 'vokalia':'http://icant.co.uk', 'brent':'http://google.com', });
this creates links in page matches keyword, overwrites existing hrefs if matches. how can improve ignore existing links?
no jquery please.
you can fix appending negated sets reg expression in order discard words prefixed >
, suffixed <
.
edit: better approach might build negative lookahead in order disallow text contained inside tags.
edit again: better if negative lookahead works anchor tags:
var linkword = function(obj){ for(i in obj){ var x = document.body.innerhtml; var linkstart = '<a href="'+obj[i]+'">'; var linkend = '</a>'; var reg = new regexp("\\b(" + + ")\\b(?![^<]*>|[^<>]*<\/[a])","ig"); x = x.replace(reg, " " + linkstart + + linkend + " "); document.body.innerhtml = x; console.log(document.body.innerhtml); } console.log(obj); } linkword({ 'the':'http://www.example.com', 'vokalia':'http://icant.co.uk', 'behind':'http://google.com', });
note spaces added before , after replaced string since regex strip them.
edit: working demo here.
edit2: working demo second solution here.
edit3: working demo third solution here.
Comments
Post a Comment