views:

45

answers:

4
var string = $.trim("How are you ? are you fine ?");
var part = $.trim("How are you ? are you fine ?");

var SearchResult = string.match(part);

if (SearchResult != null && part!="") {
    alert("hello1");
}


string = $.trim("How are you ? a");
part = $.trim("How are you ? a");

SearchResult = string.match(part);

if (SearchResult != null && part!="") {
    alert("hello2");
}

string = $.trim("How are you ?");
part = $.trim("How are you ?");

SearchResult = string.match(part);

if (SearchResult != null && part!="") {
    alert("hello3");
}

Only the third alert works; what is the problem in first and second string ?

+2  A: 

I think the problem is that you have a question mark in the string which gets parsed as a special regex character. You should try escaping it as \? .

teukkam
A: 

Should be:

part = $.trim("How are you \\? a")
Zafer
+1  A: 

When match is called with a non-RegExp object, it is converted to a RegExp:

If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).

That means since ? is a special character in regular expressions (meaning the preceding expression may be repeated zero or one time) you need to escape it with \?. And since the \ also needs to be escaped in string declarations, you will need:

var part = $.trim("How are you \\? are you fine \\?");

An easier way would be to use indexOf that returns the index of the begin of the match and -1 if there was no match:

string.indexOf(part) > -1
Gumbo
A: 

Actually, the first two alerts are working correctly; the third one only matches by accident. If you print the result of the match, you'll see there's no question mark at the end. As the other responders said, ? is a metacharacter, so /How are you ?/ matches the sequence "How are you", optionally followed by a space.

As the others said, if you want to match a literal question mark you have to escape it. And if you want to force the regex to match the whole string or nothing, you need to anchor it at both ends:

/^How are you \?$/
Alan Moore