I want to get the number of occurrences of a character in a given string. String and character are variable.
I have the following code, in this example I want to get the number of ? in the string:
var myString = 'Where is my string?';
var myCharacter = '?';
var characterCount = 0;
characterCount = (myString.match(new RegExp(myCharacter, 'g')) || []).length;
alert(characterCount);
The above code works fine for characters other than the ones that have a meaning in regular expressions such as ?, *, , . but it doesn’t work for these characters.
How can I modify the regex to also match these special characters and give the correct result?