[英]javascript test method not working as expected
I have a conditional logic based on the OS
version no. 我有一个基于
OS
版本号的条件逻辑。 in the browser useragent
string. 在浏览器的
useragent
字符串中。
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
. 我总是收到
3
的警报。
I tried replacing test
method with indexOf
and i get an alert with 5
. 我尝试用
indexOf
替换test
方法,并收到5
的警报。
Can somebody explain why (/3./).test(useragent)
returns true? 有人可以解释为什么
(/3./).test(useragent)
返回true吗?
You always get this because your regex /3./
means - match 3 and any symbol behind it. 总是得到这个,因为您的正则表达式
/3./
表示-匹配3及其后面的任何符号。 You have to escape the .
您必须逃脱
.
. 。
For example try /3\\./
, and respectively for the others: /2\\.3/
, /4\\./
. 例如,分别尝试
/3\\./
,其他的分别尝试:/2 /2\\.3/
,/4 /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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.