2 ° Aggiornamento: Nel tentativo di fornire una risposta completa, sto Benchmarking the tre metodi proposti nelle varie risposte.
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
var i;
// Testing the substring method
i = 0;
console.time('10k substring');
while (i < 10000) {
testURL.substring(0, testURL.indexOf('?'));
i++;
}
console.timeEnd('10k substring');
// Testing the split method
i = 0;
console.time('10k split');
while (i < 10000) {
testURL.split('?')[0];
i++;
}
console.timeEnd('10k split');
// Testing the RegEx method
i = 0;
var re = new RegExp("[^?]+");
console.time('10k regex');
while (i < 10000) {
testURL.match(re)[0];
i++;
}
console.timeEnd('10k regex');
Risultati in Firefox 3.5.8 su Mac OS X 10.6.2:
10k substring: 16ms
10k split: 25ms
10k regex: 44ms
risultati in Chrome 5.0.307.11 su Mac OS X 10.6.2:
10k substring: 14ms
10k split: 20ms
10k regex: 15ms
Nota che il metodo della sottostringa è di funzionalità inferiore in quanto restituisce una stringa vuota se l'URL non contiene una stringa querystring. Gli altri due metodi restituirebbero l'URL completo, come previsto. Tuttavia è interessante notare che il metodo della sottostringa è il più veloce, specialmente in Firefox.
1 ° UPDATE: In realtà il metodo split() suggested by Robusto è una soluzione migliore che quello che ho suggerito in precedenza, dal momento che funziona anche quando non v'è alcuna querystring:
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.split('?')[0]; // Returns: "/Products/List"
var testURL2 = '/Products/List';
testURL2.split('?')[0]; // Returns: "/Products/List"
Risposta originale:
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?')); // Returns: "/Products/List"
fonte
2010-03-29 20:21:08
Possibile duplicato di [Come rimuovere l'hash da window.location (URL) con JavaScript senza aggiornamento della pagina?] (Https://stackoverflow.com/questions/1397329/how-to -remove-the-hash-from-window-location-url-con-javascript-senza-page-r) – PayteR