javascript test method not working as expected -
javascript test method not working as expected -
i have conditional logic based on os
version no. in browser useragent
string.
here code 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 alert 3
.
i tried replacing test
method indexof
, alert 5
.
can explain why (/3./).test(useragent)
returns true?
you because regex /3./
means - match 3 , symbol behind it. have escape .
.
for illustration seek /3\./
, , respectively others: /2\.3/
, /4\./
.
your code should 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"); }
javascript
Comments
Post a Comment