.split() not working as expected in IE8

后端 未结 5 758
Happy的楠姐
Happy的楠姐 2021-01-13 03:48

I\'m using the following to extract variables from a URL contained in a variable. It works fine in modern browsers but in IE8 it fails on the first variable but succeeds on

相关标签:
5条回答
  • 2021-01-13 04:25

    Do you need to use split here? Can you not just use match:

    var h = p.match(/height=([0-9]+)/)[1];
    

    As browsers have some bugs using split with a regex http://blog.stevenlevithan.com/archives/cross-browser-split. If you do need to use split with a regex cross browser you could look at xregexp which is a library that fixes regexs across browsers.

    0 讨论(0)
  • 2021-01-13 04:40

    Use p.match(regex) instead:

    http://jsfiddle.net/B42tM/3/

    /* Get Height */
    var h = p.match(/height=([0-9]+)/);
    h = h[1];
    if (!h) {h = 500};
    alert(h);
    
    /* Get Width */
    var w = p.match(/width=([0-9]+)/);
    w = w[1];
    if (!w) {w = 800};
    alert(w);
    
    0 讨论(0)
  • 2021-01-13 04:41

    You can find both dimensions with a match or exec expression:

    var p = 'http://sagensundesign.com?height=400&width=300';
    
    var siz=p.match(/((height|width)=)(\d+)/g);
    
    
    alert(siz)
    
    /*  returned value: (Array)
    height=400, width=300
    */
    
    0 讨论(0)
  • 2021-01-13 04:43

    There is a normalisation script which should fix the inconcistencies you are seeing. http://blog.stevenlevithan.com/archives/cross-browser-split

    0 讨论(0)
  • 2021-01-13 04:50

    There have been some valid responses, but you may be interested in a function I use to retrieve GET parameters from URLs.

    var get = function (name, url) { // Retrieves a specified HTTP GET parameter. Returns null if not found.
        url = (typeof (url) === "undefined" ? window.location.href : url);
    
        var regex = new RegExp("[?&]" + name + "=([^&#]*)");
        var results = regex.exec(url);
        var output = (results ? results[1] : null);
    
        return output;
    };
    

    You could use it like this.

    var url = 'http://sagensundesign.com?height=400&width=300';
    
    var h = get("height",url);
    var w = get("width",url);
    
    0 讨论(0)
提交回复
热议问题