zeshanshani
10/7/2016 - 4:54 AM

Check if a string contains any URLs and wrap them all into HTML <a> tags.

Check if a string contains any URLs and wrap them all into HTML tags.

/**
 * 
 * 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>