views:

28

answers:

3

I would like to convert any instances of a hashtag in a String into a linked URL:

#hashtag -> should have "#hashtag" linked.
This is a #hashtag -> should have "#hashtag" linked.
This is a [url=http://www.mysite.com/#name]named anchor[/url] -> should not be linked.
This isn't a pretty way to use quotes -> should not be linked.

Here is my current code:

String.prototype.parseHashtag = function() {
 return this.replace(/[^&][#]+[A-Za-z0-9-_]+(?!])/, function(t) {
  var tag = t.replace("#","")
  return t.link("http://www.mysite.com/tag/"+tag);
 });
};

Currently, this appears to fix escaped characters (by excluding matches with the amperstand), handles named anchors, but it doesn't link the #hashtag if it's the first thing in the message, and it seems to grab include the 1-2 characters prior to the "#" in the link.

Halp!

+1  A: 

How about the following:

/(^|[^&])#([A-Za-z0-9_-]+)(?![A-Za-z0-9_\]-])/g

matches the hashtags in your example. Since JavaScript doesn't support lookbehind, it tries to either match the start of the string or any character except & before the hashtag. It captures the latter so it can later be replaced. It also captures the name of the hashtag.

So, for example:

subject.replace(/(^|[^&])#([A-Za-z0-9_-]+)(?![A-Za-z0-9_\]-])/g, "$1http://www.mysite.com/tag/$2");

will transform

#hashtag
This is a #hashtag and this one #too.
This is a [url=http://www.mysite.com/#name]named anchor[/url]
This isn't a pretty way to use quotes

into

http://www.mysite.com/tag/hashtag
This is a http://www.mysite.com/tag/hashtag and this one http://www.mysite.com/tag/too.
This is a [url=http://www.mysite.com/#name]named anchor[/url]
This isn't a pretty way to use quotes

This probably isn't what t.link() (which I don't know) would have returned, but I hope it's a good starting point.

Tim Pietzcker
+1  A: 

There is an open-source Ruby gem to do this sort of thing (hashtags and @usernames) called twitter-text. You might get some ideas and regexes from that, or try out this JavaScript port.

Using the JavaScript port, you'll want to just do:

var linked = TwitterText.auto_link_hashtags(text, {hashtag_url_base: "http://www.mysite.come/tag/"});
bcherry
This is great for Twitter, but we're not using Twitter. We'll take a look at the codebase though, thanks.
Martindale
while the library is designed to work with tweets, it'll link up hashtags in any text, and you can point the generated URLs wherever you'd like.
bcherry
A: 

Tim, your solution was almost perfect. Here's what I ended up using:

subject.replace(/(^| )#([A-Za-z0-9_-]+)(?![A-Za-z0-9_\]-])/g, "$1<a href=\"http://www.roleplaygateway.com/tag/$2\"&gt;#$2&lt;/a&gt;");

The only change is the first conditional, changed it to match the beginning of the string or a space character. (I tried \s, but that didn't work at all.)

Martindale