[英]Remove url param with regex
Given a url, I'm trying to remove a particular url parameter. 给定一个url,我正在尝试删除特定的url参数。
For example, if I had: 例如,如果我有:
http://example.com?foo=bar&baz=boo
And I wanted to get rid of foo=bar
and be left with: 我想摆脱foo=bar
并留下:
http://example.com?baz=boo
Or if I wanted to remove baz=boo
I would be left with: 或者,如果我想删除baz=boo
我会留下:
http://example.com?foo=bar
I'm trying to use a regular expression along with the string's replace
function. 我正在尝试使用正则表达式以及字符串的replace
函数。
Here's what I have: 这就是我所拥有的:
// s is "foo"
new RegExp("([&?]+)" + s + "=.*&")
It's not working for the case of: 它不适用于以下情况:
http://example.com?foo=bar
Because it's not matching the &
, but I can't figure out how to craft the regex to handle both of these situations. 因为它与&
不匹配,但我无法弄清楚如何制作正则表达式来处理这两种情况。
([&?]+)foo=.*?(?:&|$)
should work. ([&?]+)foo=.*?(?:&|$)
应该有效。
.*?
fixes greediness issues. 解决了贪婪问题。 (?:&|$)
is a non-capturing group. (?:&|$)
是一个非捕获组。 It either matches a &
or it matches the line end (with $
). 它匹配一个&
或它匹配行结束(用$
)。 str = str.replace(/(?:\?|&)(foo[^=]*=[^&]+)(?:&|$)/,'');
I think that what you looking for, using group to deal with the both cases with &
and without it : 我认为你在寻找什么,使用group来处理这两种情况, &
和不使用它:
"([&?]+)" + s + "=(.*&|.*$)?"
Edit : Update fiddle 编辑: 更新小提琴
You could add ?
你可以加?
if you want to stop on the first occurance of &
(if exist) : 如果你想在&
(如果存在)的第一次出现时停止:
"([&?]+)" + s + "=(.*?&|.*$)?"
_____________________^
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.