Replacing a string using Regular Expression based on certain conditions

When working with a node.js server, I encountered the need to modify URL addresses using JavaScript in a specific way:

For instance:

hostX/blah/dir1/name/id.js?a=b --> name.hostY/dir2.js?guid=id&a=b

Another example:

hostZ/dir1/name/id.js --> name.hostY/dir2.js?guid=id

This transformation is achieved by utilizing string.replace and applying regular expressions defined within a configuration file.

My current attempt looks like this:

url.replace(/.*\\/dir1\\/(.*)\\/\\(d{2})\\.js?:(?=\?)(.*)/, "$1.hostC\/dir2.js?guid=$2");

The replacement string specifies ?guid=id. Should I adjust the expression or the replacement string so that &originalQueryString (with an ampersand) is included for Example 1, while nothing extra is added for Example 2?

Answer №1

Here is a solution that should fit your examples:

text.replace(/.*?\/dir1\/([^\/]+)\/(.*?)\.js\??(.*)/i, "$1.hostC/dir2.js?guid=$2&$3").replace(/&$/, "")

If needed, you can adjust the regex options to include 'g' or 'm' based on your specific requirements.

Answer №2

One possible way to express this is:

/([^/]+)\/([^./]+)\.js(?:\?(.*))?$/

For Instance

> "hostA/blah/dir1/name/id.js".replace(/([^/]+)\/([^./]+)\.js(?:\?(.*))?$/, "$1.hostC/dir2.js?guid=$2&$3")
< "hostA/blah/dir1/name.hostC/dir2.js?guid=id&"

> "hostA/blah/dir1/name/id.js?a=b".replace(/([^/]+)\/([^./]+)\.js(?:\?
(.*))?$/, "$1.hostC/dir2.js?guid=$2&$3")
< "hostA/blah/dir1/name.hostC/dir2.js?guid=id&a=b"

If you encounter issues with the trailing &, consider splitting the regex into two statements,

< "hostA/blah/dir1/name/id.js".replace(/([^/]+)\/([^./]+)\.js$/, "$1.hostC/dir2.js?guid=$2")
> "hostA/blah/dir1/name.hostC/dir2.js?guid=id"

> "hostA/blah/dir1/name/id.js?a=b".replace(/([^/]+)\/([^./]+)\.js(?:\?(.*))$/, "$1.hostC/dir2.js?guid=$2&$3")
< "hostA/blah/dir1/name.hostC/dir2.js?guid=id&a=b"

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

Executing React Fetch API Twice upon loading the page

Double-fetching Issue with React Fetch API on Initial Page Load import React, { useState, useEffect } from 'react' import axios from 'axios'; import { Grid, Paper, TextField } from '@mui/material' import PersonOut ...

Associating functions with events within objects

I am encountering a unique issue with jQuery and JavaScript in general. Currently, I am developing a JS file that allows me to create portlets for a client's website. I am utilizing SignalR to send updates to the users. The code snippet below is cau ...

Adding a class to an element in AngularJS

I have a question about entering empty values in an input field and highlighting its boundary. I added a new class 'warning' for this purpose and created the following code. HTML: `<body ng-app="TestPage"> <form ng-controller="TestFor ...

Refresh all fields for various products with a single click of a button

Our Magento multi-vendor site allows vendors to easily manage their products. For each single product, vendors can view and update information such as price, selling price, quantity, and more from their vendor account. We have implemented a feature where ...

Utilizing Promise.all to update subdocuments with Mongoose

Encountered an error while checking the value in promiseArr, seeking assistance or suggestions for a better approach. Thanks! **Error** <rejected> { MongooseError: Callback must be a function, got [object Object] at new MongooseError (D:\P ...

The initial attempt to use autocomplete with Jquery UI is not functioning as expected upon entry

I'm facing a frustrating issue that's driving me crazy. I'm not an expert in javascript, but I believe the solution is simple. I'm using jQuery UI autocomplete with data retrieved from Ajax. The problem is, I only get the desired resul ...

Tips for effectively managing loading state within redux toolkit crud operations

Seeking guidance on efficiently managing the loading state in redux-toolkit. Within my slice, I have functionalities to create a post, delete a post, and fetch all posts. It appears that each operation requires handling a loading state. For instance, disp ...

The input text in the Typeahead field does not reset even after calling this.setState

As I work on creating a watchlist with typeahead functionality to suggest options as the user types, I encountered an issue where the text box is not resetting after submission. I attempted the solution mentioned in this resource by calling this.setState( ...

Switch up the font style of the title element

Is it possible to modify the font-family of the title attribute in an input field using either JavaScript or jQuery? <input type="text" title="Enter Your Name" id="txtName" /> ...

Using angularjs, populate a dropdown menu by enclosing the options in curly braces

Utilizing the curly braces syntax interpolation in AngularJS allows us to connect data from the model to the view. This technique is typically used for displaying text. Is there a way to populate a dropdown list using the {{}} syntax? ...

What is the best method for utilizing dynamically assigned keys within a JSON object?

I am currently working with Rhino and I need to find a way to utilize a variable in order to define the key of a map. Here's an example of what I'm trying to achieve: var name = "Ryan"; var relationshipType = "brother"; var relatedName = "David" ...

Determine if a specific identifier is already present using Javascript or Jquery

Is there a way to determine if an html tag with its specific id is present more than once in the code? This is my pseudocode for checking: if($('#myId').length > 1) { // It exists twice } ...

@keyframes shimmering-fade

I'm attempting to create a text animation effect (please see video) but I'm struggling to find the solution!! Can someone assist me with this? Should I use JavaScript for a better result? h1.fadeinone { animation: fadeinone 10s;} h1.fadeintwo ...

Error: react-router v4 - browserHistory is not defined

I'm diving into the world of creating my very first React app within Electron (also my first experience with Electron). I have two routes that need to navigate from one to another. Here's the code snippet I am using: Root ReactDOM.render( < ...

How to show dates in AngularJS using local formatting

One situation I'm dealing with involves setting a date for an event. The challenge is that the date picker needs to display the date in a localized format based on the country or region. I've been exploring various solutions in AngularJS, but so ...

Unable to access $_POST parameters in PHP when making an Ajax request

My HTML file is shown below: <script> var xml = new XMLHttpRequest(); xml.onreadystatechange = function(){ if (xml.readyState === 4 && xml.status === 200) { console.log(xml.responseText); } } xml ...

Tips for relocating a div panel below all other div panels when a button is clicked with JQuery and CSS

There are several panels stacked below each other. Each panel has a button that, when clicked by the user, should move the panel to the bottom of the stack. For example: If there are 10 panels aligned sequentially and the user wants to remove Panel 2 by ...

Blocking the space bar in JavaScript is a useful technique that can be

I'm in the process of developing an application and I'm looking to prevent the space bar from scrolling my page My framework of choice is VUE, and I am trying to trigger a method using an event handler However, when I attempt to call the ' ...

The concept of CSS "preload" animation

When working with CSS, I encountered an issue with lag while loading 24 different mask images for a transition effect. To address this, I tried using a div called "preload" to cache the images and prevent lag on playback: <div class='trans' s ...

Implementing a document update event using jQuery

On my WordPress site, I am using a responsive lightbox plugin. When an image is clicked, it opens a popup box with the ID fullResImage. Now, I would like to incorporate the Pinch Zoomer function to it. Do I need to bind a function for this, or is there a s ...