Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.split() not working as expected in IE8

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 the second.

var p = 'http://sagensundesign.com?height=400&width=300';

/* Get Height */
var h = p.split(/height=([0-9]+)/);
h = h[1];
if (!h) {h = 500};
alert(h);

/* Get Width */
var w = p.split(/width=([0-9]+)/);
w = w[1];
if (!w) {w = 800};
alert(w);

UDPATE:

Here is the working solution... http://jsfiddle.net/cssguru/B42tM/

like image 440
Adam Youngers Avatar asked Feb 28 '12 20:02

Adam Youngers


2 Answers

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.

like image 95
slashnick Avatar answered Oct 27 '22 21:10

slashnick


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);
like image 24
Rick Kuipers Avatar answered Oct 27 '22 22:10

Rick Kuipers