loading...
Cover image for Remove params from URL in JavaScript

Remove params from URL in JavaScript

adamkdean profile image Adam K Dean ・1 min read

Let us say the param we want to remove is session and our URL is http://www.example.com/?session=lasgfnasolgnasgn&id=500&other=100. We can remove it like so:

var oldUrl = "http://www.example.com/?session=lasgfnasolgnasgn&id=500&other=100";
var newUrl = oldUrl.replace(/&?session=([^&]$|[^&]*)/gi, "");
console.log(newUrl);

http://www.example.com/?id=500&other=100

Now let's say we also want to remove other from that URL, we can do that like this:

var oldUrl = "http://www.example.com/?session=lasgfnasolgnasgn&id=500&other=100";
var newUrl = oldUrl.replace(/&?((session)|(other))=([^&]$|[^&]*)/gi, "");
console.log(newUrl);

http://www.example.com/?id=500

Excellent.

Posted on by:

adamkdean profile

Adam K Dean

@adamkdean

Principal Network Engineer / Master of Engineering (Mechanical) student

Discussion

markdown guide