2012-02-28 19 views
5

Estoy usando lo siguiente para extraer variables de una URL contenida en una variable. Funciona bien en los navegadores modernos, pero en IE8 falla en la primera variable pero tiene éxito en la segunda..split() no funciona como se esperaba en IE8

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:

Aquí está la solución de trabajo ... http://jsfiddle.net/cssguru/B42tM/

+0

Split tiene varios errores en su implementación en varios navegadores web. Algunos son casos extremos, otros no. Sugiero que eche un vistazo a lo siguiente para ver si puede replicar el error y luego usar esa información para idear una solución alternativa. http://blog.stevenlevithan.com/archives/cross-browser-split – michaelward82

Respuesta

6

Do necesitas usar dividido aquí? Puede que no sólo tiene que utilizar match:

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

Como los navegadores tienen algunos errores usando split con una expresión regular http://blog.stevenlevithan.com/archives/cross-browser-split. Si necesita utilizar split con un navegador de expresiones regulares cruzadas, puede consultar xregexp, que es una biblioteca que arregla expresiones regulares en todos los navegadores.

+0

Gracias por la ayuda. –

2

Uso p.match (expresiones regulares) en su lugar:

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

¡Gracias por la ayuda! –

0

Puede encontrar ambas dimensiones con un partido o expresión Exec:

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 
*/ 
1

ha habido algunas respuestas válidas, pero que pueden estar interesados ​​en una función que utilizo para recuperar GET parámetros de URL.

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; 
}; 

Podrías usarlo así.

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

var h = get("height",url); 
var w = get("width",url); 
Cuestiones relacionadas