Regex to match special characters like ? * \

Hi,

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?

Thanks.

Hi,

AFAIK there is no in-built way of escaping special characters for this purpose.

You could however, write one:

escapeSpecialChars = function(string) {
  return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};

ref: JavaScript: How to generate a regular expression from a string

This would give you:

escapeSpecialChars = function(string) {
  return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};

var myString = 'Where is my string?';
var myCharacter = escapeSpecialChars('?');
var characterCount = 0;
characterCount = (myString.match(new RegExp(myCharacter, 'g')) || []).length;
console.log(characterCount);

// Output: 1
1 Like

Thanks, that worked nicely.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.