Stacks
Stacks

Reputation: 369

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

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

I have a string of paragraph lines that looks like this (saved from a textarea):

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

How would I replace each URL, http://www.example.com and http://duckduckgo.com, with:

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

Such that all URLs become rendered as links, the text of which excludes the 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"

To render this:

Here are some links

www.example.com is one of them

and duckduckgo.com is another

From a handlebars helper..

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

Upvotes: 2

Views: 4699

Answers (1)

user3886234
user3886234

Reputation:

This works with the example string you provided:

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

Example on JSFiddle.

--edit--

Now that you've updated the question, here is a handlebars helper you can use:

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

And a working example on JSFIddle.

Upvotes: 2

Related Questions