remove parameter from url via regex
The third argument to pushState()
is the entire URL. Your function is sending only the location.search
i.e. query parameter part of the URL. So you'll need to do
window.history.pushState({}, '', location.pathname + parameters)}
on your function's last line. Also, your code is currently not handling the edge cases i.e. if you remove first parameter, it removes the ?
and not the trailing &
. So you end up with http://example.com/products&brand=apple
which isn't a valid URL. And finally, I simplified your expression a bit.
const reg = new RegExp('[?&](' + key + '=[\\w-]+&?)');
let matches = reg.exec(parameters);
if (matches){
parameters = parameters.replace(matches[1], '');
}
This still doesn't handle more complex cases (params without values, hash etc). There are a couple of other options:
- Dump the regex and go with a
split('&')
based solution. More code, but a lot more readable and less error-prone. If you don't need IE support, use
URLSearchParams
. Then your entire function can be reduced to this:var params = new URLSearchParams(location.search);
params.delete(key);
window.history.pushState({}, '', location.pathname + "?" + params.toString());
Remove querystring parameters from url with regex
A regular expression is probably more than you need.
You could do the following to remove the ?
and everything (query
string + hash) after it:
var routeData = route.split("?")[0];
If you truly wanted to strip only the query string, you could preserve
the hash by reconstructing the URL from the window.location
object:
var routeData = window.location.origin + window.location.pathname + window.location.hash;
If you want the query string, you can read it with window.location.search
.
Regular expression to remove one parameter from query string
If you want to do this in just one regular expression, you could do this:
/&foo(=[^&]*)?|^foo(=[^&]*)?&?/
This is because you need to match either an ampersand before the foo=..., or one after, or neither, but not both.
To be honest, I think it's better the way you did it: removing the trailing ampersand in a separate step.
Javascript how to remove parameter from URL sting by value?
If you are targeting browsers that support URL and URLSearchParams you can loop over the URL's searchParams
object, check each parameter's value, and delete() as necessary. Finally using URL's href
property to get the final url.
var url = new URL(`https://www.example.com/test/index.html?param1=4¶m2=3¶m3=2¶m4=1¶m5=3`)
//need a clone of the searchParams//otherwise looping while iterating over//it will cause problemsvar params = new URLSearchParams(url.searchParams.toString());for(let param of params){ if(param[1]==3){ url.searchParams.delete(param[0]); }}console.log(url.href)
regex to remove a particular query parameter
This is the regex you should use:
\/(.*)\/\?lang=.*
Basically you were using =*
at the end of yours which means: Matches between zero and unlimited times the =
character and that wasn't be able to match anything after =
.
Using lang=.*
means:
lang=
matches the characters lang= literally (case sensitive).*
matches any character (except for line terminators)
remove url parameters using javascript
There are several ways for this one of them is
var url="http://bulk-click.startappsdasdasice.com/tracking/adClick?d=scsdc%20cdcsc%20c";var suburl=url.substring(0,url.lastIndexOf("/")).replace(/(^\w+:|^)\/\//, '');console.log(suburl);
Regex for removing part of URL param
You can use this regex in Javascript for searching:
/[?&]pIds=[^&]*$|([?&])pIds=[^&]*&/
RegEx Breakup:
[?&]pIds=[^&]*$
: Match?
or&
followed bypIds=
.$
ensures this is the only parameter in query string.|
: OR([?&])pIds=[^&]*&
: Match?
or&
followed bypIds=
followed by&
. This is the case where there is one more parameter in query string.
Code:
var arr=['?pIds=123,2311','?pIds=123,2311&deal=true','?pIds=123','?pIds=123&deals=true','&pIds=123,2311','&pIds=123,2311&deals=true','&pIds=123','&pIds=123&deals=true'];
var re = /[?&]pIds=[^&]*$|([?&])pIds=[^&]*&/;
for (i=0; i<arr.length; i++) { console.log(arr[i], ' => ', arr[i].replace(re, '$1'));}
JS RegEx to remove part of a URL?
you can use the .replace() method
let URL = "some random URL you have"
console.log(URL.replace('&edge=curl',''))
Will replace every "&edge=curl" that it finds in this string and replace it with '' an empty string which is basically removing it.
You can also use the same method .replace() to replace any static URL variables like "img=1"
console.log(URL.replace('img=1','img=2'))
Related Topics
Change Image on Scroll Position
Image Upload With Preview and Delete Option - Javascript/Jquery
Filereader Onload With Result and Parameter
Select Drop Down Text-Align Center in Safari
React History.Push() Not Rendering New Component
Ant Design Range Picker Disable Array of Dates
Sum of Numbers in an Array With JavaScript
After Clicking a Button of Sweet Alert Call PHP File
Ajax - How to Use a Returned Array in a Success Function
React Component Not Refreshing When Redux State Has Been Updated With Successful Action
Looping Through Dynamically Generated Checkboxes to Get Values
How to Style Dynamically Created Elements With CSS
Get Index on Click of a Mapped Array in React Js
Reinitialize/Reset Dropzone After Form Is Submitted
How to Display All Imagefrom Array in Reactjs
How to Override the Onbeforeunload Dialog and Replace It With My Own