0

Possible Duplicate:
Is there a RegExp.escape function in Javascript?

I'm currently using: var keywords = new RegExp(req.params.keywords, 'i');

The catch is, if req.params.keywords == '.*', this will match anything, what I want is for it to match .* literally, as in \.\*\

Is there a more elegant solution than escaping every passed single character with a \?

Community
  • 1
  • 1
bevacqua
  • 47,502
  • 56
  • 171
  • 285
  • In the process of showing what you mean, you almost solved your own problem. Just remove that last `backslash (\)` and you are done. – Rohit Jain Jan 30 '13 at 15:42

1 Answers1

2

If you want to match literally, instead of using the regular expressions included in the string, don't use a regular expression. Use the string indexOf() function to see if a string is contained withing another one.

For case insensitive matching, you convert each string to, say, lower case before the match.

var searchForString = req.params.keywords.toLowerCase();
var searchInString = xxx.toLowerCase();
if (searchInString.indexOf(searchForString) >= 0) {
    ... then it matches ...
}
Lee Meador
  • 12,829
  • 2
  • 36
  • 42