从 JavaScript 中的 URL 中删除查询参数
我正在尝试编写一个函数,该函数将从 javascript 中的 url 中删除查询参数。我想我使用正则表达式来实现它,但我不确定我是否错过了任何东西。另外,我无法摆脱这种感觉,可能有更好的方法来做到这一点,而不需要我花半天时间摆弄正则表达式,并且冒着后来发现我没有采取某种角落的风险情况考虑在内。
remove_query_argument = function(url, arg){
var query_arg_regex;
// Remove occurences that come after '&' symbols and not the first one after the '?'
query_arg_regex = new RegExp('&' + arg + '=[^(?:&|$)]*', 'ig');
url = url.replace(query_arg_regex, '');
// remove the instance that the argument to remove is the first one
query_arg_regex = new RegExp('[?]' + arg + '[^(?:&|$)]*(&?)', 'i');
url = url.replace(query_arg_regex, function (match, capture) {
if( capture != '&' ){
return '';
}else{
return '?'
}
});
return url;
}
有没有人看到这段代码有任何问题,或者想建议更好的实现或方法来解决这个问题?
谢谢!
I'm trying to write a function that will remove a query argument from a url in javascript. I think I have it using regex, but I'm not sure if I've missed anything. Also, I can't shake the feeling that there was probably a better way to do this that didn't involve me messing around with regex half the day and running the risk of later finding out that I didn't take some kind of corner case into account.
remove_query_argument = function(url, arg){
var query_arg_regex;
// Remove occurences that come after '&' symbols and not the first one after the '?'
query_arg_regex = new RegExp('&' + arg + '=[^(?:&|$)]*', 'ig');
url = url.replace(query_arg_regex, '');
// remove the instance that the argument to remove is the first one
query_arg_regex = new RegExp('[?]' + arg + '[^(?:&|$)]*(&?)', 'i');
url = url.replace(query_arg_regex, function (match, capture) {
if( capture != '&' ){
return '';
}else{
return '?'
}
});
return url;
}
Does anyone see any problems with this code or would like to suggest a better implementation or way of going about this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你有很多与 URL 相关的操作,你最好尝试一下这个很棒的 js 库 https://github.com /medialize/URI.js
If you have a lot of URL-related operations, you better try this awesome js library https://github.com/medialize/URI.js
给定一个 百分比编码 URL,以下函数将从其查询中删除字段值对字符串:
一些示例:
Given a percent-encoded URL, the following function will remove field-value pairs from its query string:
Some examples: