如何用JavaScript/jQuery替换和缩短一段文本中的超链接

How to replace and shorten hyperlinks in a paragraph of text with JavaScript/jQuery?

本文关键字:一段 文本 超链接 JavaScript 何用 jQuery 替换      更新时间:2023-09-26

假设我有一段文字:

The Northrop Grumman X-47B https://en.wikipedia.org/wiki/Northrop_Grumman_X-47B 
is a demonstration unmanned combat air vehicle (UCAV) designed for carrier-based 
operations.

我想替换文本中的超链接并将其转换为真正的超链接。同时,我想将超链接的措辞缩短为固定的 20 个字符,以便用户阅读的文本更短,例如

  • 诺斯罗普·格鲁曼公司的X-47B https://en.wikipedia.org...是一种演示无人作战飞行器(UCAV),专为基于航母的操作。

因此,文本中链接的代码可能如下所示:

<a href="https://en.wikipedia.org/wiki/Northrop_Grumman_X-47B">https://en.wikipedia.org...</a>

我环顾四周,发现了一些例子,但它们根本不起作用。我只想要一个标准的JavaScript函数来做到这一点。也就是说,一个接受纯文本(不是 HTML)并可以转换文本的函数。不确定如何同时防范XSS。

我怀疑它会涉及循环遍历文本的每个部分的组合,然后使用一些正则表达式来查找 URL,提取它,然后使用 substr() 缩短 URL,然后以某种方式将其替换为文本。知道怎么做吗?

感谢您的帮助。

像这样:

$('p').html(function(_,txt) {
    var exp = /('b(https?|ftp|file):'/'/[-A-Z0-9+&@#'/%?=~_|!:,.;]*[-A-Z0-9+&@#'/%=~_|])/ig;
    return txt.replace(exp, function(l) {
        return '<a href="'+l+'">'+l.substr(0,20)+'...</a>'
    }); 
});

小提琴

使用此脚本

<script>
function convertlink(text) {
    var urlRegex = /(https?:'/'/[^'s]+)/g;
    return text.replace(urlRegex, function(url) {
        return '<a href="' + url + '">' + geturl(url) + '</a>';
    })
}
function geturl(url){
    if(url.length > 20){
     return url.substr(0,20) + "...";
    } else { 
     return url;
    }
}
var str = "The Northrop Grumman X-47B https://en.wikipedia.org/wiki/Northrop_Grumman_X-47B is a demonstration unmanned combat air vehicle (UCAV) designed for carrier-based operations."
alert(convertlink(str));
</script>

我编辑了批准的答案以返回您需要的内容。这将替换链接文本,而不考虑链接(即,它不是指向维基百科的链接)。

function replaceURLWithHTMLLinks(text) {
  var exp = /('b(https?|ftp|file):'/'/[-A-Z0-9+&@#'/%?=~_|!:,.;]*[-A-Z0-9+&@#'/%=~_|])/ig;
  return text.replace(exp, function ($1) {
    return '<a href="' + $1 + '">' + $1.slice(0, 20) + '...</a>';
  });
}

小提琴