从URL中删除查询字符串

问题描述:

在Javascript中从路径中删除查询字符串的简单方法是什么?
我见过一个使用window.location.search的Jquery插件。我不能那样做:我的案例中的URL是一个从AJAX设置的变量。

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.

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


获得这个的简单方法是:

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

编辑

@caub(最初是@crl)提出了一个更简单的组合,适用于查询字符串和哈希(虽然它使用RegExp,以防任何人遇到问题):

@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):

function getPathFromUrl(url) {
  return url.split(/[?#]/)[0];
}