Find URL’s in string and convert them to links – JavaScript

If you need to find the url's in a string and convert them to HTML link elements using JavaScript, feel free to take this handy regex expression:

function parseLinks(string) {
  const exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig
  
  return string.replace(exp,`<a href='$1'>$1</a>`)
}

console.log ( parseLinks('Follow this https://www.google.com') );

// Output:
// Follow this <a href='https://www.google.com' target='_blank'>https://www.google.com</a>"Code language: JavaScript (javascript)

Source

Leave a Reply

Your email address will not be published. Required fields are marked *