第二次更新:为了提供一个全面的答案,我正在对各种答案中提出的三种方法进行基准测试。
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');
在 Mac OS X 10.6.2 上的 Firefox 3.5.8 中的结果:
10k substring: 16ms
10k split: 25ms
10k regex: 44ms
在 Mac OS X 10.6.2 上的 Chrome 5.0.307.11 中的结果:
10k substring: 14ms
10k split: 20ms
10k regex: 15ms
请注意,substring 方法的功能较差,因为如果 URL 不包含查询字符串,它会返回一个空白字符串。如预期的那样,其他两种方法将返回完整的 URL。然而有趣的是 substring 方法是最快的,尤其是在 Firefox 中。
第一次更新: 实际上 split() 方法suggested by Robusto 是比我之前建议的更好的解决方案,因为即使没有查询字符串它也可以工作:
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"
原答案:
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?')); // Returns: "/Products/List"