I need JavaScript special regex pattern to convert the input string to required string.
Input String:
google.com/q=abc?param1=[foo,bar]&optional=true¶m2=[bar,baz]
Output String:
google.com/q=abc?param1=foo&optional=true¶m2=bar
This is my code.
function transformUrl(inputUrl) {
var pattern = /[([^,]]+),([^,]]+)]/g;
var outputUrl = inputUrl.replace(pattern, function (match, group1) {
return group1;
});
return outputUrl;
}
var inputUrl = "google.com/q=abc?aparam1=[foo,bar]&optional=true¶m2=[bar,baz]";
var outputUrl = transformUrl(inputUrl);
console.log(outputUrl); // google.com/q=abc?aparam1=foo&optional=true¶m2=bar`
As you can see, main problems is solved but ‘¶’ string has been changed to ‘¶’ string.
How can I fix this issue?
Thanks in advance for your help!
2
Answers
You can simplify this by looking at each parameter in turn using the URL API instead of trying to do it all at once.
This assumes that you have a URL which includes a protocol (e.g.
http:
orhttps:
). It should be trivial to prepend one of you don’t though and remove it afterwardsIf you want to use regex then, use anyone of them, which is better for your:
or