-1

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
  • 561,645
  • 34
  • 376
  • 476
Saurabh Kumar
  • 15,763
  • 47
  • 125
  • 205

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
  • 61,521
  • 14
  • 148
  • 143
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
  • 46,019
  • 20
  • 127
  • 142
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,657
  • 15
  • 18
  • There are a whole bunch of regex metacharacters: "[", "]", "(", ")", ".", "*", "?", "{", "}", "\", "|", "^", "$", ... – Pointy May 25 '11 at 12:46