user557419
user557419

Reputation:

JavaScript function doesn't return correct value

I'm developing a function in which I'd like to check which useragent is currently being used.
The following code is just a prototype and it returns whatever value it reads first - in this case IE.

detectDevice = function () {
    var userAgent = {
        detect: function () {
            return navigator.userAgent;
        },
        detectBrowser: function () {
            var browser = userAgent.detect();
            var currentBrowser;
            return currentBrowser = browser.indexOf('IE') ? "Internet Explore" : browser.indexOf('Mozilla') ? "FireFox" : "UserAgent not recognized!";
        },
        version: function (identifier) {
        }
    };

    alert(userAgent.detectBrowser());
}

I can't tell what's wrong. Maybe you guys can see it and tell me where I made a wrong turn.

Upvotes: 0

Views: 141

Answers (3)

Murtaza
Murtaza

Reputation: 3065

You are not checking the value of the index...

if you find the indexOf('IE') >= 0 hould be your line...

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

return (browser.indexOf('IE') > -1)
           ? "Internet Explorer" 
           : (browser.indexOf('Mozilla') > -1)
                ? "FireFox" 
                : "UserAgent not recognized!";

Upvotes: 2

Rob W
Rob W

Reputation: 348972

indexOf returns -1 if no match is found. If a match is found, the returned value is the character index of the found substring.

To check whether a substring exists, you should use:

browser.indexOf('IE') != -1
// If a match is found, a non-negative index is returned. So, this also works:
//..... indexOf('IE') > -1
// .... indexOf('IE') >= 0

Upvotes: 6

Related Questions