gpt4 book ai didi

javascript - 将字符串中的 URL 替换为包含匹配 URL 的 HTML 字符串的 Handlebar Helper?

转载 作者:行者123 更新时间:2023-11-29 21:52:25 24 4
gpt4 key购买 nike

There is a similar question, but the result is comparatively specific..

我有一串看起来像这样的段落行(从文本区域保存):

"Here are some links\n\nhttp://www.example.com is one of them\n\nand http://duckduckgo.com is another"

我如何将每个 URL http://www.example.comhttp://duckduckgo.com 替换为:

<a href="http://www.example.com" target="_blank">www.example.com</a>
and
<a href="http://duckduckgo.com" target="_blank">duckduckgo.com</a>

这样所有 URL 都呈现为链接,其文本不包括 http://..

"Here are some links\n\n<a href="http://www.example.com" target="_blank">www.example.com</a> is one of them\n\nand <a href="http://duckduckgo.com" target="_blank">duckduckgo.com</a> is another"

渲染这个:

这里是一些链接

www.example.com就是其中之一

duckduckgo.com是另一个

来自 Handlebars 助手..

Handlebars.registerHelper('linkingplaintext', function(plaintext) {
// some code to replace the URLs with their equivalent links
return new Handlebars.SafeString(linkedplainText);
});

最佳答案

这适用于您提供的示例字符串:

var text = "Here are some links\n\nhttp://www.example.com\n\nLorem ipsum dolor\n\nhttp://www.example.com"

var urls = text.split('\n').filter(function(v) {
return v.indexOf('http') > -1;
});

$.each(urls, function(i,v) {
$('<a></a>').attr('href', v).html(v).appendTo('body');
$('body').append('<br />');
});

关于 JSFiddle 的示例.

--编辑--

现在您已经更新了问题,这里是您可以使用的 Handlebars 助手:

Handlebars.registerHelper('wrapURL', function(str) {
str = Handlebars.Utils.escapeExpression(str);

var matches = str.match(/http\S+/);
var wrapped = matches.map(function(v, i, a) {
return '<a href="' + v + '">' + v + '</a>';
});

for (var i = 0; i < matches.length; i++) {
str = str.replace(matches[i], wrapped[i]);
}

return new Handlebars.SafeString(str)
});

还有一个关于 JSFIddle 的工作示例.

关于javascript - 将字符串中的 URL 替换为包含匹配 URL 的 HTML 字符串的 Handlebar Helper?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28402021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com