segunda actualización: En un intento de dar una respuesta integral, estoy evaluación comparativa de los tres métodos propuestos en las distintas respuestas.
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');
Resultados en Firefox 3.5.8 en Mac OS X 10.6.2:
10k substring: 16ms
10k split: 25ms
10k regex: 44ms
resultados en Chrome 5.0.307.11 en Mac OS X 10.6.2:
10k substring: 14ms
10k split: 20ms
10k regex: 15ms
Nota que el método de subcadena es inferior en funcionalidad ya que devuelve una cadena en blanco si la URL no contiene una cadena de consulta. Los otros dos métodos devolverían la URL completa, como se esperaba. Sin embargo, es interesante observar que el método de subcadena es el más rápido, especialmente en Firefox.
primera ACTUALIZACIÓN: En realidad, el método split() suggested by Robusto es una mejor solución que la que sugirió anteriormente, ya que funcionará incluso cuando no hay una cadena de consulta:
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"
Original Respuesta:
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?')); // Returns: "/Products/List"
Posible duplicado de [¿Cómo eliminar el hash de window.location (URL) con JavaScript sin actualización de página?] (Https://stackoverflow.com/questions/1397329/how-to -remove-the-hash-from-window-location-url-with-javascript-without-page-r) – PayteR