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
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.
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);
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
*/
There is a normalisation script which should fix the inconcistencies you are seeing. http://blog.stevenlevithan.com/archives/cross-browser-split
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);