Search code examples
javascriptregexunicodereserved-words

Count Occurrences of Reserved Characters in Regexp (Javascript)


I am trying to count the occurrences of normally reserved characters in Regexp in a given string. So for example, the asterisk (*) is a reserved character in Regexp. So, while I can do this:

var textareaId = document.getElementById("textareaId").value;
var occ = (textareaId.match(/i/g) || []).length;
alert(occ);

I can't do this:

var textareaId = document.getElementById("textareaId").value;
var occ = (textareaId.match(/*/g) || []).length;
alert(occ);

I tried using the unicode equivalent of an asterisk (\u002A), escaping the asterisk, using a Regexp constructor, and putting the asterisk in an array, but it dosen't seem to match. It always gives this error when I put it directly in the variable occ:

Uncaught SyntaxError: Unexpected token *

This also applies to all other reserved characters in regexp (brackets, parenthesis, carrots, etc.).

Any help would be greatly appreciated.


Solution

  • You should escape the asterisk with a backslash (\).

    Here is an exampel:

    str = 'alskjdfalk*sdjf alksdjf* aljsdf01830*912838123*'
    var occ = (str.match(/\*/g) || []).length;
    console.log(occ);