Eliminar a cadea URL

2ª actualización:. Nun intento de dar unha resposta integral, son unha avaliación comparativa dos tres métodos propostos nas diferentes respostas

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';var i;// Testing the substring methodi = 0;console.time('10k substring');while (i < 10000) { testURL.substring(0, testURL.indexOf('?')); i++;}console.timeEnd('10k substring');// Testing the split methodi = 0;console.time('10k split');while (i < 10000) { testURL.split('?'); i++;}console.timeEnd('10k split');// Testing the RegEx methodi = 0;var re = new RegExp("+");console.time('10k regex');while (i < 10000) { testURL.match(re); i++;}console.timeEnd('10k regex');

Os resultados en Firefox 3.5.8 en Mac OS X 10.6.2:

10k substring: 16ms10k split: 25ms10k regex: 44ms

Os resultados en Chrome 5.0.307.11 en Mac OS X 10.6.2:

10k substring: 14ms10k split: 20ms10k regex: 15ms

Teña en conta que o método de subcadena é menor na funcionalidade que devolve unha cadea en branco se a URL non contén unha cadea de consulta. Os outros dous métodos devolverían a URL completa, como se esperaba. Non obstante, é interesante notar que o método de subcadeno é o máis rápido, especialmente en Firefox.

Primeira actualización: en realidade, o método Split () suxerido por Robust é unha mellor solución que a que suxire anteriormente, xa que funcionará mesmo cando non hai cadea de consulta:

V ID = “

Resposta orixinal:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';testURL.substring(0, testURL.indexOf('?')); // Returns: "/Products/List"

Deixa unha resposta

O teu enderezo electrónico non se publicará Os campos obrigatorios están marcados con *