Eliminate web address parameter using regular expressions

Looking to remove a specific URL parameter from a given URL.

For instance, if the URL is:

http://example.com?foo=bar&baz=boo

And I want to eliminate foo=bar to get:

http://example.com?baz=boo

Or removing baz=boo would leave me with:

http://example.com?foo=bar

Attempting to achieve this using regular expressions and the string's replace function.

This is my approach so far:

// s is "foo"
new RegExp("([&?]+)" + s + "=.*&")

This does not work for cases like:

http://example.com?foo=bar

The issue lies in not matching the &, struggling to adapt the regex for both scenarios.

View jsBin

Answer №1

Check out this working fiddle

If you're looking to handle both cases with and without the use of &, you can try this:

"([&?]+)" + s + "=(.*&|.*$)?"

Update: Updated fiddle here

To stop at the first occurrence of & (if it exists), you can add a ? like this:

"([&?]+)" + s + "=(.*?&|.*$)?"
_____________________^

I hope this explanation helps.

Answer №2

([&?]+)foo=.*?(?:&|$) is the suggested solution.

Modifications Made

  • .*? was added to address greediness issues.
  • (?:&|$) is a non-capturing group that matches either a & or the end of the line ($).

Answer №3

string = string.replace(/(?:\?|&)(bar[^=]*=[^&]+)(?:&|$)/,'');

EXAMPLE

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is server-side rendering necessary for `browserHistory` in React Router?

I am a beginner in the world of React and currently diving into the complexities of routing. While hashHistory (/#/paths/like/this) proves to be functional, browserHistory (/paths/like/this) appears much cleaner. However, I noticed that when reopening URLs ...

What is the best way to delete markers from a leaflet map?

I need to remove markers from my map. I am looking to create a function that will specifically clear a marker based on its ID. I am utilizing Leaflet for the map implementation. Here is my function: public clearMarkers(): void { for (var id in this. ...

I am encountering an issue where body-parser is not functioning properly with typescript. Whenever I make a request, the request.body is returning as undefined

Below is the code snippet for my Express application using TypeScript version 3.7.4: import bodyParser from "body-parser"; import config from "config"; import cookieParser from "cookie-parser"; import express from "express"; import mongoose from "mongoose ...

Apply the cursor property to the audio element and set it as a pointer

I have a question: how can I apply a cursor style to my <audio> controls? When I try to add them using CSS, the cursor only appears around the controls and not directly on the controls themselves. Below is the code snippet: <audio class="_audio" ...

What is the reason for using a wrapper with fs.readFile when a callback is included as an argument?

Recently delving into Node.js, I encountered a perplexing scenario while using fs.readFile(). Initially, my attempt to read a file led me to use: fs.readFile("file.txt",function(err,data) { if(err) {throw err;} console.log(data); }); However, to ...

What is the best way to implement an anchor link in my JavaScript code?

I'm struggling to wrap my head around this, as my thoughts seem to have vanished. On my webpage, there's a button element with an id: for example <button id="someId"></button> Within the document.ready function, I've set up an ...

Having trouble retrieving a dynamic name with Formcontrol error?

I keep encountering a typeError in this section of code <p *ngIf="formValue.controls['{{obj.name}}'].invalid, but when I manually enter it like this *ngIf="formValue.controls['uname'].invalid it works perfectly fine. What ...

HTML5 Canvas Border

Hey Everyone, I've been working on an HTML5 canvas project where I set the canvas width to $(window).width(). Everything was going smoothly until I added a border, which caused a horizontal scroll to appear. Important: I attempted to use the innerWid ...

Retrieving value from the parent scope using the conventional approach

Today I was puzzled by some unexpected behavior of AngularJS. While using console.log to log $scope, I noticed that there was no key attached to the scope named val1. However, when I used console.log($scope.val1), it returned a value as an object. After ...

Steps to trigger a dialog to appear automatically within an Icon Menu with React Material UI

In my application, I have an icon menu implemented along with an array that contains the possible values for the items in the menu. Here is an example of how the array looks: listItems = { [ { label: 'ZERO', t ...

Utilizing AngularJS element.find results in modifications to my objects

Encountering an issue with angularJS when trying to locate elements. It appears that the objects are being altered when using element.find('type').attr('id' ,someid); Here are some additional details: The directive is only used in on ...

Managing actions on dynamically generated dropdown options in <select> elements

If I have a function that generates a dropdown, it is called from a parent component where props like state key, array, and onChange function are passed in. The dropdown items are dynamically created from the array. What I want is for the parent's sta ...

The form does not seem to be updating or refreshing even after an AJAX submission and validation

I have a form set up to submit data to my database using jQuery Validate plugin and ajax. However, I'm encountering an issue where after clicking submit, the form does not clear out. While the data does get updated in the database, I need help figurin ...

When using the JavaScript .sort() method, any undefined value must always be considered as coming before any other value

I am working on sorting an array of objects based on multiple fields, typically around 3-4 fields. Some values within the objects may be undefined, and I need to ensure that these undefined values are considered as "earlier" in the sorting process, wheth ...

Issues with visuals in jQuery.animate

I have nearly finished implementing a slide down drawer using jQuery. The functionality I am working on involves expanding the drawer downwards to reveal its content when the handle labeled "show" is clicked, and then sliding the drawer back up when the ha ...

Using Javascript to dynamically populate dropdown options based on radio button selection

I am in the process of developing a basic form that allows users to input the frequency of a specific report. Initially, users were only able to enter days of the week. However, due to changes in demand for certain reports, options such as workday and day ...

Displaying [object Object] in Angular Material datatable

I am currently working on implementing a datatable component using Express and Firebase DB. Below is the service request data: getText() { return this.http.get<nomchamp[]>(this.url) .map(res => { console.log(res); return res }); ...

Creating a carousel of cards using JavaScript, CSS, and HTML

Here is a visual reference of what I'm attempting to achieve: https://i.stack.imgur.com/EoQYV.png I've been working on creating a carousel with cards, but I'm struggling to synchronize the button indicators with card advancement when clicke ...

Can you explain the distinction between compiled and interpreted programming languages?

Despite my efforts to research the topic, I am still confused about the distinction between a compiled language and an interpreted language. It has been mentioned that this is one of the distinguishing factors between Java and JavaScript. Can someone ple ...

Issue with floating date and time not functioning properly in ICS file for Yahoo Calendar

I have set up a calendar event in Google, Apple, and Yahoo calendars for each individual customer. The event is scheduled based on the customer's address at a specific time, so there should be no need for timezone conversion. However, I encountered an ...