0

Search on my site is implemented using regular expression:

RegExp(name, 'i')

where "name" is value of input block. The problem is that dot matches any character and when I input dot, search gives wrong results. How should I change pattern of regular expression to exclude this issue?

techfoobar
  • 65,616
  • 14
  • 114
  • 135
abstractmind
  • 107
  • 10
  • What regular expression are you using? There is no dot here. – Evan Knowles Mar 28 '13 at 12:51
  • Escape the regular expression – tckmn Mar 28 '13 at 12:51
  • If you don't want regular expression functionality, why are you using a regular expression? – Sepster Mar 28 '13 at 12:51
  • I think, I did not explain correctly. In variable "name" could be any text, including letters, digits and punctuation signs. The way I want my regular expression to work: if there are dots in my search text, i want it to be determined not as regular expression metacharacter, which means any character except newline, but as an ordinary dot symbol. I know how to make it, when I set reg exp pattern by myself (like /\\./), but I don't know how to add this pattern to pattern, that is being set by "name" variable. – abstractmind Mar 28 '13 at 13:14

2 Answers2

0

If you don't want to allow certain regular expressions, then you could do a search/replace to escape these values, such that eg . becomes \..

You'd need to clarify in your prompt that certain regular expressions will be treated as literals.

Sepster
  • 4,800
  • 20
  • 38
0

You should create some regex escapper to escape all meta characters.

I think this function will fit: (found in Is there a RegExp.escape function in JavaScript?)

RegExp.escape= function(s) {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
Community
  • 1
  • 1
Wouter J
  • 41,455
  • 15
  • 107
  • 112