views:

1950

answers:

4

Hi,..simple questions 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 esaping it with "\" but the doesn't work either.....is there another way to use "?" literally instead of as a special character?

Thanks, Andrew

+7  A: 

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

Jon
… one for the regex and one for the string declration.
Gumbo
makes sense...thanks
Andrew
A: 
"I like your Apartment\\x2E Could we schedule a viewing\\x3F My"
Tolgahan Albayrak
+3  A: 

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 "\?"

CMS
makes sense...thanks
Andrew
+3  A: 

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;
jiggy