I've been using Javascript string.match(*regex*)
function to parse the navigator.userAgent
string.
FYI, According to MDN & W3schools:
"The match() method searches a string for a match against a regular expression, and returns the matches, as an Array object."
I first parse once to get the wanted strings for the base string:
var userAgent = navigator.userAgent;
var splitted = userAgent.match(/[(][^)]+[)]|\w+\/\S+/ig);
Which gives me the following Output (Which is an Array)
Mozilla/5.0
(Macintosh; Intel Mac OS X 10_10_3)
AppleWebKit/537.36
(KHTML, like Gecko)
Chrome/41.0.2272.76
Safari/537.36
Then i parse the Navigator/Version type strings in a for loop
for (var i = 0; i < splitted.length; i++ ) {
var str = splitted[i];
if (str[0] == '(') {
} else {
var name = str.match(/[^\/]+/i);
var version = str.match(/[0-9|\.]+/i);
}
But, very surprisingly and even though I get the desired result, I get a String Object for the name and an Array Object for the version
How is it even possible ?
Here's the snippet of the code (fiddle):
var userAgent = navigator.userAgent;
var splitted = userAgent.match(/[(][^)]+[)]|\w+\/\S+/ig);
var outputDiv = document.getElementById("log");
for (var i = 0; i < splitted.length; i++ ) {
var str = splitted[i];
if (str[0] == '(') {
} else {
var name = str.match(/[^\/]+/i);
var version = str.match(/[0-9|\.]+/i);
outputDiv.innerHTML += name.toString() + " is a " + typeof(name) + "<br>";
outputDiv.innerHTML += version.toString() + " is a " + typeof(version) + "<br>";
}
};
<div id="log"></div>
--- UPDATE ---
Thanks FactoryAidan for the answer, it was a scope problem.
Conclusion: be careful when naming global variables :)