Reputation: 5286
I'm building two regex helpers.
The first replaces any links with an anchor tag. Here's how it looks:
String.prototype.parseURL = function() {
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=@]+/g, function(url) {
return url.link(url);
});
};
The second replaces any Twitter handles (starting with @
) with an anchor tag that points to the appropriate Twitter profile. Here's how it currently looks:
String.prototype.parseUsername = function() {
return this.replace(/\s[@]+[A-Za-z0-9-_]+/g, function(u) {
var username = u.replace("@","")
return u.link("http://twitter.com/"+username);
});
};
Both of these prototype methods are then chained on a string, which replaces the appropriately matched inputs. A previous edge case that I fixed involved the @
symbol within a hyperlink.
There's one edge case that I'm not meeting, which is when a Twitter handle is at the beginning of a string (with no characters in front of it, no whitespace, etc).
How can I have parseUsername
match any instances of @
that do not have any characters such as slashes/tags/hyphens/etc. in front of it but are the first instance in the first word of a string?
Here's an image of what's going on:
Upvotes: 3
Views: 55