0

I am in need of a function that determines URL occurences in a message (string) and wraps them in <a> elements.

This is my approach:

function wrapUrl(message){

    var content = message.split(' ');

    content.forEach(function(item){

        // Check if this is an URL and if so, wrap it

    });

}

This will be used in a chatroom, thus there will be a lot of messages. Each message is a POJO holding 3 key - value pairs.

Considering performance, is this a good approach or am I missing a easier variant?

user2422960
  • 1,476
  • 6
  • 16
  • 28

2 Answers2

2

You can use:

function wrapUrl(message){

    var regex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/g;

    var message2 = message.replace(regex, function(v) { return "<a>" + v + "</a>"});

    return message2;
}
sergiomse
  • 775
  • 12
  • 18
0

check this out:

var regex = new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");

if(regex.test("http://google.com")){
  alert("Successful match");
}else{
  alert("No match");
}
Community
  • 1
  • 1
user733421
  • 497
  • 4
  • 14
  • Thank you for the regEx sample! However, what i really wanted to know was whether or not it is an issue that I have to split up and loop every single message in order to find the occurences (which could be multiple ones) – user2422960 Sep 03 '14 at 09:27
  • as long as the message is not huge, it's ok, but I'd rather message.replace. – user733421 Sep 03 '14 at 09:51