Detect URLs in text with JavaScript

后端 未结 13 2208
孤城傲影
孤城傲影 2020-11-22 06:23

Does anyone have suggestions for detecting URLs in a set of strings?

arrayOfStrings.forEach(function(string){
  // detect URLs in strings and do something sw         


        
13条回答
  •  不要未来只要你来
    2020-11-22 07:09

    Here is what I ended up using as my regex:

    var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    

    This doesn't include trailing punctuation in the URL. Crescent's function works like a charm :) so:

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

提交回复
热议问题