解析文本以格式化内容中的 URL 并缩短 URL

Parse text to format URLs from content and shorten URLs

本文关键字:URL 文本 格式化      更新时间:2023-09-26

我想将以下文本解析为带有锚标记的格式化 URL:

something is wrong with http://www.gbin1.com/index.html,  but cannot find the reason in http://www.google.com

如何将上面的文本 URL 替换为 <a href="url">url</a>并使用 JavaScript 缩短它,如下所示:

something is wrong with <a href="http://www.gbin1.com/index.html">gbin1.com</a>,  but cannot find the reason in <a href="http://www.gbin1.com">google.com</a>

检查此解决方案。

var x = "something is wrong with http://www.gbin1.com/index.html,  but cannot find the reason in http://www.google.com";
var expression = /[-a-zA-Z0-9@:%_'+.~#?&//=]{2,256}'.[a-z]{2,4}'b('/[-a-zA-Z0-9@:%_'+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var split = x.split(" ");
for(var i=0; i< split.length; i++){
    if(split[i].match(regex)){
        var text = split[i].split(".").slice(1).join(".").split("/")[0];
        split[i] = '<a href='"' +split[i]+''">'+text+'</a>';
    }
}
console.log(split.join(" "));

http://jsfiddle.net/4JGY7/