2015-02-09 38 views
2

There is a similar question, but the result is comparatively specific..手把助手用包含匹配URL的HTML字符串替换字符串中的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.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> 

这样所有的网址都会显示为链接,其文本排除了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); 
}); 

回答

2

这适用于你所提供的例子字符串:在JSFiddle

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 />'); 
}); 

例。

- 编辑 -

现在你已经更新的问题,这里是一个车把帮手,你可以使用:

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工作的例子。

+0

感谢您的强烈的示例..已更新的问题与一个更可变的字符串,可能会发生,其中可能包括文本之前给定的链接 – Stacks 2015-02-09 03:11:01

+0

真正辉煌 – Stacks 2015-02-09 06:13:22