0

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!

Ronan
  • 407
  • 3
  • 5
  • 13

3 Answers3

2

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));
Community
  • 1
  • 1
Ivan
  • 34,531
  • 8
  • 55
  • 100
  • If the content has the URL as "google.com", will this work, the restriction of "(https?|ftp|file):\/\/" part can be modified as optional value – BHUVANESH MOHANKUMAR Aug 13 '16 at 17:46
  • Wow this works really nicely, thank you! It even works for multiple occurrences (which I forgot to mention). Thanks for the snippet! – Ronan Aug 13 '16 at 17:48
1

Just complement of @Ivan answer

You can use regx and replace() function

var string = "I am a string (http://google.com)";
var output = string.replace(/(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))/,"<$1>");
console.log(output);

Hope this will help

Aman Rawat
  • 2,625
  • 1
  • 25
  • 40
0

Look for the index of http:// and then the end will be the first time it encounters a non-url-allowed character (space, non-alphanumeric with exceptions for /,.,#, etc.).

This would be the most general way to start, but could be optimized as you monitor the links you are consuming with it.

Jecoms
  • 2,558
  • 4
  • 20
  • 31
  • Alright, I;ve got a good idea on how to find the multiple indexes; how would I look for the first non-allowed character? I imagine string.split() at the start of the index and then scan the remainder of a string? I'm not quite certain how I would do that last portion. – Ronan Aug 13 '16 at 17:41