将字符串中的URL替换为包含匹配URL的HTML字符串的Handlebar帮助程序
Handlebar Helper to Replace URL in String with HTML String Containing the Matching URL?
还有一个类似的问题,但结果比较具体。。
我有一串段落行,看起来像这样(从文本区域保存):
"Here are some links'n'nhttp://www.example.com is one of them'n'nand http://duckduckgo.com is another"
如何将每个URL http://www.example.com
和http://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的工作示例。
相关文章:
- Datatables查询url字符串:需要regex来修复url解析
- 将URL字符串${userid}替换为javascript对象中的实际用户id
- PHP 在 URL 字符串中连接变量
- 如何获取目录中的URL字符串
- 正确解析 URL 字符串
- JavaScript:将 URL 字符串转换为唯一标识符
- 传递的URL字符串未解释为字符串
- 如何获取django视图的url字符串
- 获取选中复选框的所有值,并将其用于url字符串
- 查找任何未定义的变量并从url字符串中隐藏
- 使用url字符串更改js/jquery的状态
- 替换 URL 字符串中的撇号时出现问题
- 在 URL 字符串中传递参数字符串
- XMLHttpRequest POST 请求到当前 URL 的有效 URL 字符串
- 如何修剪和拆分 URL 字符串
- Ember.js:使用模型实例的路由获取模型实例的 url 字符串
- jquery 正则表达式修剪 URL 字符串的开头和结尾
- 将 URL 字符串传递给 Javascript 函数
- 如何测试 URL 字符串是绝对字符串还是相对字符串
- 使用 javascript 从 URL 字符串中删除特定事件