Fouad
Fouad

Reputation: 409

Add a dot between javascript output

I'm using the following javascript to detect iOS Version

var iOS = parseFloat(
    ('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0,''])[1])
    .replace('undefined', '3_2').replace('_', '.').replace('_', '')
) || false;

the problem is that the script is showing 7.06 instead of 7.0.6

how can i add a "." between the last 2 numbers?

tried messing with the code and changing some stuff but couldn't make it

i'm newbie in javascript, thank you :)

Upvotes: 2

Views: 106

Answers (2)

Travis J
Travis J

Reputation: 82287

The issue is that parseFloat masks the real problem, namely that your replace is slightly off. You start out correct, as in

('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/gi.exec(navigator.userAgent) || [0,''])[1])

yields "7_0_6". However, the replace only hits the first _ and converts this string to "7.0_6" (the next "_" -> "" removes the last underscore which is how you get 7.06). Make the replace do a global replace and it will get both.

(('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0,''])[1])
.replace('undefined', '3_2').replace(/_/gi, '.').replace(/_/gi, '')
) || false;

Will yield "7.0.6".

Upvotes: 2

Paul Draper
Paul Draper

Reputation: 83273

Well, the problem is this: parseFloat. You want a string, not a number. A number can have only one decimal point.

Just try:

var iOS = ('' + (/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent) || [0,''])[1])
.replace('undefined', '3_2').replace('_', '.').replace('_', '') || false;

Upvotes: 1

Related Questions