How to replace plain URLs with links?

前端 未结 24 2300
生来不讨喜
生来不讨喜 2020-11-21 05:42

I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing t

24条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 06:08

    Here's my solution:

    var content = "Visit https://wwww.google.com or watch this video: https://www.youtube.com/watch?v=0T4DQYgsazo and news at http://www.bbc.com";
    content = replaceUrlsWithLinks(content, "http://");
    content = replaceUrlsWithLinks(content, "https://");
    
    function replaceUrlsWithLinks(content, protocol) {
        var startPos = 0;
        var s = 0;
    
        while (s < content.length) {
            startPos = content.indexOf(protocol, s);
    
            if (startPos < 0)
                return content;
    
            let endPos = content.indexOf(" ", startPos + 1);
    
            if (endPos < 0)
                endPos = content.length;
    
            let url = content.substr(startPos, endPos - startPos);
    
            if (url.endsWith(".") || url.endsWith("?") || url.endsWith(",")) {
                url = url.substr(0, url.length - 1);
                endPos--;
            }
    
            if (ROOTNS.utils.stringsHelper.validUrl(url)) {
                let link = "" + url + "";
                content = content.substr(0, startPos) + link + content.substr(endPos);
                s = startPos + link.length;
            } else {
                s = endPos + 1;
            }
        }
    
        return content;
    }
    
    function validUrl(url) {
        try {
            new URL(url);
            return true;
        } catch (e) {
            return false;
        }
    }
    

提交回复
热议问题