showing results for - "js detect link in string"
Nicole
08 Apr 2017
1function replaceURLs(message) {
2  if(!message) return;
3 
4  var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
5  return message.replace(urlRegex, function (url) {
6    var hyperlink = url;
7    if (!hyperlink.match('^https?:\/\/')) {
8      hyperlink = 'http://' + hyperlink;
9    }
10    return '<a href="' + hyperlink + '" target="_blank" rel="noopener noreferrer">' + url + '</a>'
11  });
12}
13 
14replaceURLs("Visit www.cluemediator.com and subscribe us on https://www.cluemediator.com/subscribe for regular updates.")
15// Output: Visit <a href="http://www.cluemediator.com" target="_blank" rel="noopener noreferrer">www.cluemediator.com</a> and subscribe us on <a href="https://www.cluemediator.com/subscribe" target="_blank" rel="noopener noreferrer">https://www.cluemediator.com/subscribe</a> for regular updates.
16