Venkata Krishna
Venkata Krishna

Reputation: 4305

How to make hashtags,urls and usernames in a string like twitter using Jquery

I am trying to make HASHTAGS, URLS and Usernames in twitter tweet string should be like links using regex. I am trying to some regex but i am going somewhere wrong. Please find my code below.

$text = "Check out @Bersin tips for building a successful #talentmanagement approach http:\/\/t.co\/27rbzMUagz"

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

String.prototype.parseUsername = function() {
    return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
        var username = u.replace("@","")
        return u.link('http://twitter.com/'+username);
    });
}
String.prototype.parseHashtag = function() {
    return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
        var tag = t.replace("#","%23")
        return t.link('http://search.twitter.com/search?q='+tag);
    });
};

    alert(text.parseURL().parseHashtag().parseUsername());

Upvotes: 0

Views: 334

Answers (1)

anubhava
anubhava

Reputation: 786359

Everywhere in your regex you're using hyphen in character class and it is unescaped. Remember that in a character class hyphen can be unescaped only when it s at 1st or last position.

1: So instead of:

/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.="]+/g

Use this:

/[A-Za-z]+:\/\/[\w-]+\.[\w:%&~?\/.="-]+/g

2: Instead of this:

/[@]+[A-Za-z0-9-_]+/g

Use this:

/@+[\w-]+/g

3: Instead of:

/[#]+[A-Za-z0-9-_]+/g

Use this:

/#+[\w-]+/g

Upvotes: 2

Related Questions