从Java脚本的路径中删除查询字符串的简便方法是什么?我已经看到了使用window.location.search的Jquery插件。我不能这样做:在我的情况下,URL是从AJAX设置的变量。
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'
一个简单的方法是:
function getPathFromUrl(url) {
return url.split("?")[0];
}
对于那些还希望在不存在querystring的情况下删除哈希(不是原始问题的一部分)的人,需要做更多的工作:
function stripQueryStringAndHashFromPath(url) {
return url.split("?")[0].split("#")[0];
}
编辑
@caub(最初为@crl)建议了一个更简单的组合,该组合适用于查询字符串和哈希(尽管它使用RegExp,以防万一有人遇到问题):
function getPathFromUrl(url) {
return url.split(/[?#]/)[0];
}
第二次更新:为了提供全面的答案,我正在对各种答案中提出的三种方法进行基准测试。
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
请注意,子字符串方法的功能较差,因为如果URL不包含查询字符串,它将返回一个空白字符串。如预期的那样,其他两个方法将返回完整的URL。但是有趣的是,substring方法是最快的,尤其是在Firefox中。
第一次更新:实际上,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"
原始答案:
var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3';
testURL.substring(0, testURL.indexOf('?')); // Returns: "/Products/List"
这可能是一个古老的问题,但我尝试使用此方法删除查询参数。似乎对我来说工作顺利,因为我需要重新加载以及删除查询参数。
window.location.href = window.location.origin + window.location.pathname;
另外,由于我使用简单的字符串加法运算,因此我猜性能会很好。但是仍然值得与这个答案中的片段进行比较
一种简单的方法是您可以执行以下操作
public static String stripQueryStringAndHashFromPath(String uri) {
return uri.replaceAll(("(\\?.*|\\#.*)"), "");
}
如果您正在使用RegEx ...
var newURL = testURL.match(new RegExp("[^?]+"))
var path = "path/to/myfile.png?foo=bar#hash";
console.log(
path.replace(/(\?.*)|(#.*)/g, "")
);
如果使用骨干.js(包含url anchor
作为路由),则URLquery string
可能会出现:
-
之前
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';
解:
window.location.href.replace(window.location.search, '');
// run as: 'http://example.com#routepath/subpath?a=1&b=3'.replace('?a=1&b=3', '');
使用标准的方法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
如果您需要对URL执行复杂的操作,可以看看jQuery url parser plugin。
(() => {
'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();
}
})();
我就是这样做的,也有RegEx支持。
文章标签:javascript , jquery
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!