简体   繁体   中英

how to parse a <a> href(s) in string with image tags

 function replaceTextFunction(g){
        var replacedText,replacePattern1,replacePattern2,replacePattern3;
        replacePattern1=/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
        replacedText=g.replace(replacePattern1,'<a href="$1" target="_blank">$1</a>');
        replacePattern2=/(^|[^\/])(www\.[\S]+(\b|$))/gim;
        replacedText=replacedText.replace(replacePattern2,'$1<a href="http://$2" target="_blank">$2</a>');
        replacePattern3=/(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;replacedText=replacedText.replace(replacePattern3,'<a href="mailto:$1">$1</a>');
        return replacedText;
        }

ok so i have me this function. Its purpose is to parse links in strings and put pretty wrappers for human clicking. It works great in that regard.

My problem is when I have an image in the string like this

<img src="http://yada.yada/image.jpg">

it parses like this

<img src="<a href="http://yada.yada/image.jpg" target="_blank">">

and of course I do not want that syntax horror to occur. Please help! :(

Try this:

function replaceTextFunction(g){
        var replacedText,replacePattern1,replacePattern2,replacePattern3;
        replacePattern1=/(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])(?![^<]+>)/gim;
        replacedText=g.replace(replacePattern1,'<a href="$1" target="_blank">$1</a>');
        replacePattern2=/(^|[^\/])(www\.[\S]+(\b|$))(?![^<]+>)/gim;
        replacedText=replacedText.replace(replacePattern2,'$1<a href="http://$2" target="_blank">$2</a>');
        replacePattern3=/(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)(?![^<]+>)/gim;replacedText=replacedText.replace(replacePattern3,'<a href="mailto:$1">$1</a>');
        return replacedText;
        }

I've added a negative lookahead to your regular expressions which make your regex ignore urls inside of HTML tags.

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