[javascript] 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?

This question is related to javascript regex literals

The answer is


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


You should use double slash:

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

Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"

And "\\?", becomes "\?"


You can delimit your regexp with slashes instead of quotes and then a single backslash to escape the question mark. Try this:

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

Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:

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

Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes 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");

And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):

_x000D_
_x000D_
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
_x000D_
_x000D_
_x000D_

A must-read: RegExp: Description at MDN.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to literals

python ValueError: invalid literal for float() SQL Server - boolean literal? Empty set literal? How do you specify a byte literal in Java? Java: how do I get a class literal from a generic type? Setting Short Value Java Can I escape a double quote in a verbatim string literal? What does the M stand for in C# Decimal literal notation? escaping question mark in regex javascript Why does instanceof return false for some literals?