Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Can someone help me to understand this code?

    I have seen this code-piece different places - to use to make a webpage redirect if it is a mobilephone.
    I don't quit understand the code - especially the line:
    if (redirectagent.indexOf(redirect_devices[i]) != -1)

    - why -1 ? Please help me - I would be so thankful.

    Code:
    <script language=javascript>
    var redirectagent = navigator.userAgent.toLowerCase();
    var redirect_devices = ['vnd.wap.xhtml+xml', 'sony', 'symbian', 'nokia', 'samsung', 'mobile', 'windows ce', 'epoc', 'nitro', 'j2me', 'midp-', 'cldc-', 'netfront', 'mot', 'up.browser', 'up.link', 'audiovox', 'blackberry', 'ericsson', 'panasonic', 'philips', 'sanyo', 'sharp', 'sie-', 'portalmmm', 'blazer', 'avantgo', 'danger', 'palm', 'series60', 'palmsource',  'smartphone', 'rover', 'au-mic', 'alcatel', 'ericy', 'vodafone', 'wap1', 'wap2', 'teleca',, 'lge', 'lg-', 'iphone', 'android', 'htc', 'dream', 'webos', 'bolt', ];
    for (var i in redirect_devices) {
    if (redirectagent.indexOf(redirect_devices[i]) != -1) {
    location.replace("http://www.example.com");
    	}
    }
    </script>
    Last edited by VIPStephan; 12-10-2011 at 02:20 AM. Reason: fixed code BB tag

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,602
    Thanks
    78
    Thanked 4,387 Times in 4,352 Posts
    The indexOf method returns -1 if the text you are searching for is *NOT* found.

    So by saying != -1 that is really saying "if the given text is found anywhere in the string...".

    It's kind of weird coding. If the useragent string contained, for example, "mot" at *ANY* place in the string (e.g., "Mosilla FireFox with remote scripting support") then it will count as "found".
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Regular Coder low tech's Avatar
    Join Date
    Dec 2009
    Posts
    852
    Thanks
    173
    Thanked 94 Times in 94 Posts
    Hi

    why -1 ?
    This post #5 may also help to claify things if you are still a little unsure about what indexOf does and why it returns -1


    Negative One condition check


    LT
    "The greatest revenge is to accomplish what others say you cannot do."
    ~ Unknown

    I used to be indecisive, but now I'm not so sure.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •