how to put links in tag a with js

Viewed 23

I need some help from JavaScript developers

I have a chat box where I send their own message with the input, and they may send a link along with the message, and I want to put the links that are sent next to the messages in a tag so that they can be clicked.

for example

 <div class="messages"> hello my friend this is your link  https://strackoverflow.com  see you later </div>

Now I want to select all the divs that have the messages class And check its string if it contains http and there is a space at the end of http Put that part of the link inside the a tag with target _blank

1 Answers

Please check below js code, i hope it will help you.

  function urlLink(text) {
  var urlRegex = /(https?:\/\/[^\s]+)/g;
  return text.replace(urlRegex, function(url) {
    return '<a href="' + url + '">' + url + '</a>';
  })
  // or alternatively
  // return text.replace(urlRegex, '<a href="$1">$1</a>')
}

var text = 'Find me at http://www.example.com and also at http://stackoverflow.com dfasdfasd asdfasdf asdfas';
var html = urlLink(text);

console.log(html)
Related