0

I have a search box in my jsp page . When the user types something in the search box a suggest list is displayed.

I have something like the below code which generates the suggest list dynamically

  sampleQuery.replace(new RegExp("("+query+")","ig"),'Foo'); ...(1)

Now the query object is the string which the user types in the search box. When I typoe in something like "?Foo" in firebug it gives javascript error on line 1. I suspect "?" is part of regular expression that's why it's throwing error.

How I can resolve the problem?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

3 Answers3

0

See the following page that I found by searching for javascript escape regexp with Google:

http://simonwillison.net/2006/Jan/20/escape/#p-6

Ferdinand Beyer
  • 64,979
  • 15
  • 154
  • 145
0

You could beforehand either:

  • escape all characters with a special meaning (such as ?*|. etc)
  • assume all none alphanumerical characters needs to be escaped.

Since the latter is easier I'll give you an example of it:

query = query.replace(/[^a-zA-Z0-9]/g, "\\$&");
sampleQuery.replace(new RegExp("("+query+")","ig"),'Foo'); ...(1)

Which for the text a?b|.c produces a\?b\|\.c.

Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
0

? is generally a regex character meaning "zero or one of the preceding character", and since ?Foo doesn't have a preceding character, it could be throwing your error. You could just prepend with a \: "\?Foo".

Rob Bailey
  • 1,747
  • 15
  • 18
  • There are a whole bunch of regex metacharacters: "[", "]", "(", ")", ".", "*", "?", "{", "}", "\", "|", "^", "$", ... – Pointy May 25 '11 at 12:46