Reputation: 1297
Supposed that I have a block of text like this:
My site: http://www.mysite.com,
drop me an email at [email protected]
I want to replace url & email address to convert text to link.
I then used this pattern for email:
text.replace(/([\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*)/gi, replacement);
and below pattern for url:
text.replace(/((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi, replacement);
But the url pattern screw up my email pattern, the last result become like:
<a href="mailto:foo@<a href="bar.com">bar.com</a>>bar.com</a>
Is there any better pattern for this situation?
Thanks
Upvotes: 0
Views: 74
Reputation: 59262
I would suggest you to go with this regex:
/(\b(?:ht|f)tps?:\/\/.+\b)|(\b[\w.]+@(?=.*?\.)[\w.]+\b)/g
And replace it with:
<a href="$1$2">$1$2</a>
Upvotes: 1
Reputation: 53498
Well, I think your core problem will be that your 'URL' pattern also contains an '@' so it'll 'match' your email address as well.
However, I would also suggest that your patterns are way too complicated. Something like:
email pattern should be something like:
[\w.+]+\@[\w.]+
url pattern something like:
https?://[\w.]+
It won't catch some of the more unusual, but otherwise valid patterns that could be used for URLs (that latter for example, won't catch URLs for CGI GETs). Neither does either really validate the data. But you don't want a regex for that in the first place really.
Upvotes: 0