从URL中删除查询字符串 [英] Remove querystring from URL

查看:152
本文介绍了从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];
}

这篇关于从URL中删除查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆