将字符串中的URL替换为包含匹配URL的HTML字符串的Handlebar帮助程序

Handlebar Helper to Replace URL in String with HTML String Containing the Matching URL?

本文关键字:URL 字符串 HTML Handlebar 帮助程序 替换 包含匹      更新时间:2023-09-26

还有一个类似的问题,但结果比较具体。。

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

"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.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.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的工作示例。