从网址中删除查询字符串


143

从Java脚本的路径中删除查询字符串的简单方法是什么?我已经看到了使用window.location.search的Jquery插件。我不能这样做:在我的情况下,URL是从AJAX设置的变量。

var testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'

Answers:


345

一个简单的方法是:

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];
}

4
+1 ...实际上,在这种情况下,split()比substring()更好。
丹尼尔·瓦萨洛

10
如果它的事项(可能不是)边际优化:split('?', 1)[0]
bobince 2010年

@ChristianVielma:这?是字符串文字,不是正则表达式。
Robusto 2013年

@Robusto对不起,我不好...我正在Java中对其进行检查(它将其解释为正则表达式):(
Christian Vielma 2013年

4
嗨,罗布斯托,为什么不.split(/[?#]/)[0]呢?
caub 2015年

32

第二次更新:为了提供全面的答案,我正在对各种答案中提出的三种方法进行基准测试。

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"

10
O_O确实非常全面,但是……为什么?最灵活,最适当的方法显然是有好处的,这里的速度绝对不重要。
deceze

1
@deceze:出于好奇...而且因为在Angus的回答中有一个关于正则表达式方法性能的争论。
丹尼尔·瓦萨洛

6
非常有趣,丹尼尔。而且,如果我不得不在页面上进行10K URL解析,我将寻求另一项工作。:)
Robusto

实际上,我可以在44毫秒内完成1万次正则表达式匹配感到有些震惊。将来,我想我会倾向于更多地使用它们。
TheGerm 2012年

12

这可能是一个古老的问题,但我尝试使用此方法删除查询参数。似乎对我来说工作顺利,因为我需要重新加载以及删除查询参数。

window.location.href = window.location.origin + window.location.pathname;

另外,由于我使用简单的字符串加法运算,所以我猜性能会很好。但是仍然值得在此答案中与摘要进行比较


3

一种简单的方法是您可以执行以下操作

public static String stripQueryStringAndHashFromPath(String uri) {
 return uri.replaceAll(("(\\?.*|\\#.*)"), "");
}

2

如果您正在使用RegEx ...

var newURL = testURL.match(new RegExp("[^?]+"))

1
regexp是一种缓慢的方法-采用简单快速的方法。
亚里士多德(Aristos)2010年

1
@Angus:您的循环正在给您“脚本可能很忙...”,因为您忘记了增量a++;。在iMac 2.93Ghz Core 2 Duo上的Firefox 3.6中修复测试,我得到了8ms的RegEx和3ms的split方法...尽管答案是+1,因为它仍然是另一种选择。
丹尼尔·瓦萨洛

1
谢谢-我几分钟前修复了它!-但要点是,即使您正在进行reg exp操作,也要讲0.000005秒,对于任何解决方案,性能都不是问题:-)
搅碎

1
match()返回一个对象。您可能不想要那样。调用toString()它(或+'')。
bobince 2010年

1
鲍勃-不错。实际上,它返回一个匹配数组-在这种情况下是一个字符串数组。所以testURL.match(新的RegExp( “[^] +”))[0]做它
压条

2
var path = "path/to/myfile.png?foo=bar#hash";

console.log(
    path.replace(/(\?.*)|(#.*)/g, "")
);

2

如果使用骨干.js(包含url anchor作为路由),则URL query string可能会出现:

  1. 之前url anchor

    var url = 'http://example.com?a=1&b=3#routepath/subpath';
  2. 之后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', '');

1

使用标准的方法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

@Brad当他做的所有事之后都返回路径名时,协议有什么关系?
的傻瓜


-3
(() => {
        '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支持。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.