简体   繁体   中英

Replacing n occurences of a certain string in a message

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?

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;
}

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM