0

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.

3
  • 2
    Have you already tried to use $.browser instead? or it's not suitable for your purposes? Commented Dec 28, 2011 at 9:34
  • 2
    What is the problem with the code above? Also, you might be interested in api.jquery.com/jQuery.browser - you could look at the jQuery source code to see how they do it. Commented Dec 28, 2011 at 9:37
  • This question is similar to: How check if a string is substring with indexof [JAVASCRIPT]. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Oct 17 at 8:12

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I'm not going to upvote this answer, since despite being correct, it doesn't describe why it works.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.