DEV Community

Cover image for Remove params from URL in JavaScript
Adam K Dean
Adam K Dean

Posted on

2 1

Remove params from URL in JavaScript

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Excellent.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay