Rimuovere la catena URL

2nd Update:. Nel tentativo di dare una risposta integrale, sono una valutazione comparativa dei tre metodi proposti nelle diverse risposte

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');

i risultati in Firefox 3.5.8 in Mac OS X 10.6.2:

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

I risultati in Chrome 5.0.307.11 in Mac OS X 10.6.2:

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

Nota che il metodo subcadena è inferiore nella funzionalità che restituisce una catena vuota se l’URL non contiene una stringa di query. Gli altri due metodi restituirebbero l’URL completo, come previsto. Tuttavia, è interessante notare che il metodo del sottocadeno è il più veloce, specialmente in Firefox.

Primo aggiornamento: In realtà, il metodo diviso () suggerito da robusto è una soluzione migliore di quella che ha suggerito in precedenza, poiché funzionerà anche quando non c’è una stringa di query:

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';testURL.split('?'); // Returns: "/Products/List"var testURL2 = '/Products/List';testURL2.split('?'); // 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"

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *