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?
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.
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.
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".
\\. 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 \.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With