Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("=)"));
like image 793
adrianmc Avatar asked Feb 14 '26 04:02

adrianmc


1 Answers

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

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.

like image 140
Patashu Avatar answered Feb 15 '26 16:02

Patashu