Javascript 从 URL 中删除查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2540969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove querystring from URL
提问by Mathias F
What is an easy way to remove the querystring from a Path in Javascript? I have seen a plugin for Jquery that uses window.location.search. I can not do that: The URL in my case is a variable that is set from AJAX.
从 Javascript 中的路径中删除查询字符串的简单方法是什么?我见过一个使用 window.location.search 的 Jquery 插件。我不能这样做:在我的例子中的 URL 是一个从 AJAX 设置的变量。
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'
回答by Robusto
An easy way to get this is:
一个简单的方法是:
function getPathFromUrl(url) {
return url.split("?")[0];
}
For those who also wish to remove the hash(not part of the original question) when no querystring exists, that requires a little bit more:
对于那些还希望在不存在查询字符串时删除散列(不是原始问题的一部分)的人,这需要多一点:
function stripQueryStringAndHashFromPath(url) {
return url.split("?")[0].split("#")[0];
}
EDIT
编辑
@caub (originally @crl) suggested a simpler combo that works for both query string and hash (though it uses RegExp, in case anyone has a problem with that):
@caub(最初是@crl)建议了一个更简单的组合,适用于查询字符串和哈希(尽管它使用 RegExp,以防有人遇到问题):
function getPathFromUrl(url) {
return url.split(/[?#]/)[0];
}
回答by Daniel Vassallo
2nd Update:In attempt to provide a comprehensive answer, I am benchmarking the three methods proposed in the various answers.
第二次更新:为了提供一个全面的答案,我正在对各种答案中提出的三种方法进行基准测试。
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');
Results in Firefox 3.5.8 on Mac OS X 10.6.2:
在 Mac OS X 10.6.2 上的 Firefox 3.5.8 中的结果:
10k substring: 16ms
10k split: 25ms
10k regex: 44ms
Results in Chrome 5.0.307.11 on Mac OS X 10.6.2:
在 Mac OS X 10.6.2 上的 Chrome 5.0.307.11 中的结果:
10k substring: 14ms
10k split: 20ms
10k regex: 15ms
Note that the substring method is inferior in functionality as it returns a blank string if the URL does not contain a querystring. The other two methods would return the full URL, as expected. However it is interesting to note that the substring method is the fastest, especially in Firefox.
请注意,子字符串方法的功能较差,因为如果 URL 不包含查询字符串,它会返回一个空白字符串。正如预期的那样,其他两种方法将返回完整的 URL。然而,有趣的是 substring 方法是最快的,尤其是在 Firefox 中。
1st UPDATE:Actually the split() method suggested by Robustois a better solution that the one I suggested earlier, since it will work even when there is no querystring:
第一次更新:实际上Robusto 建议的 split() 方法是我之前建议的更好的解决方案,因为即使没有查询字符串它也能工作:
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 Answer:
原答案:
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?')); // Returns: "/Products/List"
回答by damitj07
This may be an old question but I have tried this method to remove query params. Seems to work smoothly for me as I needed a reload as well combined with removing of query params.
这可能是一个老问题,但我已经尝试过这种方法来删除查询参数。似乎对我来说工作顺利,因为我需要重新加载以及删除查询参数。
window.location.href = window.location.origin + window.location.pathname;
Also since I am using simple string addition operation I am guessing the performance will be good. But Still worth comparing with snippets in this answer
此外,由于我使用的是简单的字符串加法操作,因此我猜测性能会很好。但仍然值得与此答案中的片段进行比较
回答by karthik m
A simple way is you can do as follows
一个简单的方法是您可以执行以下操作
public static String stripQueryStringAndHashFromPath(String uri) {
return uri.replaceAll(("(\?.*|\#.*)"), "");
}
回答by yckart
var path = "path/to/myfile.png?foo=bar#hash";
console.log(
path.replace(/(\?.*)|(#.*)/g, "")
);
回答by vikyd
If using backbone.js (which contains url anchoras route), url query stringmay appear:
如果使用backbone.js(包含url anchor路由),urlquery string可能会出现:
before
url anchor:var url = 'http://example.com?a=1&b=3#routepath/subpath';after
url anchor:var url = 'http://example.com#routepath/subpath?a=1&b=3';
之前
url anchor:var url = 'http://example.com?a=1&b=3#routepath/subpath';之后
url anchor:var url = 'http://example.com#routepath/subpath?a=1&b=3';
Solution:
解决方案:
window.location.href.replace(window.location.search, '');
// run as: 'http://example.com#routepath/subpath?a=1&b=3'.replace('?a=1&b=3', '');
回答by plodder
If you're into RegEx....
如果您喜欢 RegEx ......
var newURL = testURL.match(new RegExp("[^?]+"))
回答by golopot
An approach using the standard URL:
使用标准的方法URL:
/**
* @param {string} path - A path starting with "/"
* @return {string}
*/
function getPathname(path) {
return new URL(`http://_${path}`).pathname
}
getPathname('/foo/bar?cat=5') // /foo/bar
回答by Boris Guéry
If you need to perform complex operation on URL, you can take a look to the jQuery url parser plugin.
如果你需要对 URL 进行复杂的操作,你可以看看jQuery url parser plugin。
回答by javascript-noob
(() => {
'use strict';
const needle = 'SortOrder|Page'; // example
if ( needle === '' || needle === '{{1}}' ) {
return;
}
const needles = needle.split(/\s*\|\s*/);
const querystripper = ev => {
if (ev) { window.removeEventListener(ev.type, querystripper, true);}
try {
const url = new URL(location.href);
const params = new URLSearchParams(url.search.slice(1));
for (const needleremover of needles) {
if (params.has(needleremover)) {
url.searchParams.delete(needleremover);
window.location.href = url;
}
}
} catch (ex) { }
};
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', querystripper, true);
} else {
querystripper();
}
})();
That's how I did it, also has RegEx support.
我就是这样做的,也有 RegEx 支持。

