p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   BOOK: Beginning JavaScript 5th Edition (http://p2p.wrox.com/forumdisplay.php?f=793)
-   -   Browser Sniffing problem (http://p2p.wrox.com/showthread.php?t=99377)

irfaan102 February 17th, 2017 10:25 AM

Browser Sniffing problem
 
Hi,
The output is giving me 10 as value, whereas it should be 10.0
Here is the code:[:confused:][:confused:]

HTML Code:

<script>
var browserString = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729)";
var browserName = "MSIE";
var findingIndex = browserString.indexOf(browserName) + browserName.length + 1;
var browserVersion = parseFloat(browserString.substring(findingIndex, findingIndex+3));
document.write(browserVersion);
</script>


canolyb1 February 21st, 2017 08:02 PM

parseFloat is working fine however if the value is after the decimal is 0 the it will not be converted. If it was any number more than 0 it would be converted to a decimal.

You can test this by changing the verion to .1 o .2 and you'll see the scring is converting to a number with a floating point fine.

If you absolutely need to see the 0 then you will have to add a toFixed() method.

Also it seems to me your substring is cont capturing the whole version. Change the sunbstring to substring(findingIndex, findingIndex+4).

So the total code will look like this:

HTML Code:

var browserString = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729)";
var browserName = "MSIE";
var findingIndex = browserString.indexOf(browserName) + browserName.length + 1;
var browserVersion = parseFloat(browserString.substring(findingIndex, findingIndex+4)).toFixed(1);
document.write(browserVersion);



All times are GMT -4. The time now is 09:35 PM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.