adrianmcli
adrianmcli

Reputation: 1996

Detecting emoticons with regex in javascript

I am creating a class to detect emoticons and have the following to detect :) smilies including their various variations (=], =), [=, [:, etc.), but it doesn't work and I can't for the life of me figure out what is wrong. I'm testing it in JSFiddle.

var DetectEmoticons = {
    countHappy: function(data) {
        var pattern = new RegExp("[:/=]-?[]/)] | [[/(]-?[:/=]", "g");
        var count = (data.match(pattern) || []).length;
        return count;
    }
}
alert(DetectEmoticons.countHappy("=)"));

Upvotes: 3

Views: 1091

Answers (1)

Patashu
Patashu

Reputation: 21793

[:=;]-?[)(|\\/\]\[]|[)(|\\/\]\[]-?[:=;]

This looks like an unholy mess from hell until you break it down:

[:=;] matches one : or one = or one ;

[)(|\\/\]\[] matches one ), (, |, \ (backslashed because it is a metacharacter), /, ] (backslashed because it is a metacharacter) or [ (backslashed because it is a metacharacter). (We didn't need to backslash ) or ( because they are not metacharacters inside of a character class).

The | in the center means 'match left of me OR match right of me' and then I write the same two character classes but in reverse to match smileys that are reversed in direction.

I think the problem with your regex is here:

[]/)]

You forgot to escape the first ] with a \ so it is treated as ending the character class prematurely.

The other problem is that you thought forward slash / is used to escape. It's not, \ is used to escape, / has no special meaning in regex.

Upvotes: 6

Related Questions