Reputation: 3258
I have a conditional logic based on the OS
version no. in the browser useragent
string.
Here is the code i tried.
var useragent = "Linux; U; Android 2.2.1; en-gb; HTC_DesireZ_A7272 Build/FRG83D";
if((/2.3/).test(useragent)){
alert("2");
}
else if((/3./).test(useragent)){
alert("3");
}
else if((/4./).test(useragent)){
alert("4");
}
else {
alert("5");
}
I always get an alert with 3
.
I tried replacing test
method with indexOf
and i get an alert with 5
.
Can somebody explain why (/3./).test(useragent)
returns true?
Upvotes: 0
Views: 84
Reputation: 25682
You always get this because your regex /3./
means - match 3 and any symbol behind it. You have to escape the .
.
For example try /3\./
, and respectively for the others: /2\.3/
, /4\./
.
Your code should look something like that:
var useragent = "Linux; U; Android 2.2.1; en-gb; HTC_DesireZ_A7272 Build/FRG83D";
if ((/Android 2\./).test(useragent)){
alert("2");
} else if((/Android 3\./).test(useragent)){
alert("3");
} else if((/Android 4\./).test(useragent)){
alert("4");
} else {
alert("5");
}
Upvotes: 1