Ronan Ronan - 3 months ago 7
Javascript Question

Insert a character at the start and end of a url within a string in Javascript

The code I have will pull a string from an API somewhere and return it back in a Discord channel. In order to keep the output clean I need to surround any url with the "<" and ">" symbols.

I had originally done this with a split() function looking for spaces and strings starting with "http". However this case fails when a string holds it, for example, like so:

var string = "I am a string (http://google.com)";


So is there a way for me to scan through an entire string to find and modify these urls?

For clarity, I am looking for:

var string = "http://google.com"
//to become
var string = "<http://google.com>"


This would also have to work with "https".

Many thanks for any help on the matter!

Answer

You can use a regex to find the URL in the string and then replace it with < and >. In depth solution can be found here by @Crescent Fresh

var string = "I am a string (http://google.com)";

function url(text) {
    var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(urlRegex, function(url) {
      return '<' + url + '>';
    });
}

console.log(url(string));