Detect URLs in text with JavaScript

后端 未结 13 2282
孤城傲影
孤城傲影 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:00

    Function can be further improved to render images as well:

    function renderHTML(text) { 
        var rawText = strip(text)
        var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   
    
        return rawText.replace(urlRegex, function(url) {   
    
        if ( ( url.indexOf(".jpg") > 0 ) || ( url.indexOf(".png") > 0 ) || ( url.indexOf(".gif") > 0 ) ) {
                return '' + '
    ' } else { return '' + url + '' + '
    ' } }) }

    or for a thumbnail image that links to fiull size image:

    return '' + '' + '
    '

    And here is the strip() function that pre-processes the text string for uniformity by removing any existing html.

    function strip(html) 
        {  
            var tmp = document.createElement("DIV"); 
            tmp.innerHTML = html; 
            var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;   
            return tmp.innerText.replace(urlRegex, function(url) {     
            return '\n' + url 
        })
    } 
    

提交回复
热议问题