Escaping a question mark in regex javascript

This is a simple question that I think.

I am trying to find the appearance of a string in another string using regex in JavaScript, for example:

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'); } 

Does this not work due to the character ? .... I tried to execute it with \ , but that won't work either. Is there any other way to use ? literally instead of a special character?

+57
javascript regex literals
May 20 '09 at 20:04
source share
4 answers

You need to escape with two backslashes

 \\? 

See this for more details:

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

+94
May 20, '09 at 20:08
source share

You should use double slash:

 var regex = new RegExp("\\?", "g"); 

Why? because in javascript \ also used to remove characters in strings, therefore: "\?" becomes: "?"

And "\\?" becomes "\?"

+16
May 20 '09 at 20:09
source share

You can delimit your regular expression with a slash instead of quotation marks, and then one backslash to avoid a question mark. Try the following:

 var gent = /I like your Apartment. Could we schedule a viewing\?/g; 
+15
May 20 '09 at 20:14
source share

Whenever you have a known pattern (i.e. you do not use a variable to create RegExp), use a regular expression literal, where you need to use single backslashes to exclude special regular expression metacharacters:

 var re = /I like your Apartment\. Could we schedule a viewing\?/g; ^^ ^^ 

Whenever you need to dynamically create RegExp, use the RegExp constructor notation, where you MUST double the backslash for them to denote a literal backslash:

 var questionmark_block = "\\?"; // A literal ? var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot var re = new RegExp(initial_subpattern + questionmark_block, "g"); 

Required Reading: RegExp: Description in MDN.

+4
Feb 02 '16 at 7:26
source share



All Articles