Created
October 7, 2016 04:54
-
-
Save zeshanshani/0fec163d0d138ed4559ff59d05a35a9a to your computer and use it in GitHub Desktop.
Check if a string contains any URLs and wrap them all into HTML <a> tags.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Convert URLs in String to Anchor Links | |
* | |
* Help taken from: | |
* http://stackoverflow.com/a/34732417 | |
* | |
* Author: Zeshan Ahmed | |
* Author URI: http://www.zeshanahmed.com/ | |
* | |
*/ | |
function convertURLToLinks( str ) { | |
return str.replace(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/g, '<a href="$&" title="$&">$&</a>'); | |
} | |
// Usage | |
var str = 'some random text http://google.com some random text https://yahoo.com'; | |
str = convertURLToLinks( str ); | |
// Result: | |
// some random text <a href="http://google.com" title="http://google.com">http://google.com</a> some random text <a href="https://yahoo.com" title="https://yahoo.com">https://yahoo.com</a> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment