Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escaping question mark in regex javascript

This is a simple question I think.

I am trying to search for the occurrence of a string in another string using regex in JavaScript like so:

 var content ="Hi, I like your Apartment. Could we schedule a viewing? My phone number is: ";   var gent = new RegExp("I like your Apartment. Could we schedule a viewing? My", "g");   if(content.search(gent) != -1){         alert('worked');       }           

This doesn't work because of the ? character....I tried escaping it with \, but that doesn't work either. Is there another way to use ? literally instead of as a special character?

like image 553
Andrew Avatar asked May 20 '09 20:05

Andrew


People also ask

How do you escape a question mark in regex?

But if you want to search a question mark, you need to “escape” the regex interpretation of the question mark. You accomplish this by putting a backslash just before the quesetion mark, like this: \? If you want to match the period character, escape it by adding a backslash before it.

What is question mark in regex JavaScript?

The question mark gives the regex engine two choices: try to match the part the question mark applies to, or do not try to match it. The engine always tries to match that part. Only if this causes the entire regular expression to fail, will the engine try ignoring the part the question mark applies to.

What does escaping mean in regex?

Now, escaping a string (in regex terms) means finding all of the characters with special meaning and putting a backslash in front of them, including in front of other backslash characters. When you've done this one time on the string, you have officially "escaped the string".

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.


1 Answers

You need to escape it with two backslashes

\\? 

See this for more details:

http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm

like image 87
Jon Avatar answered Sep 24 '22 13:09

Jon