3

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("=)"));
1

1 Answer 1

6

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

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the explanation, but how come it still doesn't work? jsfiddle.net/TTWsa
You need double the backslashes, i.e. \\ becomes \\\\, and \ becomes \\. This is because of both string and RegExp escaping.
@ibopm Do you have to double up backslashes?
If it's going to be static, you can also use a RegExp literal instead of new RegExp(), and avoid the backslash issue. jsfiddle.net/TTWsa/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.