Ronan Ronan - 1 year ago 75
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 (";

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 = ""
//to become
var string = "<>"

This would also have to work with "https".

Many thanks for any help on the matter!

Answer Source

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 (";

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download