What causes the unexpected behavior of str.replace() when the replacement string contains a regex pattern?

let a =  `<script crossOrigin="anonymous" src="//example.com/index.js"></script>`

let regex = new RegExp(
            `<script(.*?) src="` + '//example.com/index.js' + `"></script>`, 'g')
let replacementString = 'document.cookie=e.replace(/[^+#$&^`|]/g,encodeURIComponent).replace("(","%28").replace(")","%29")+"="+t.replace(/[^+#$&\/:<-\[\]-}]/g,encodeURIComponent)+(r.domain?";domain="+r.domain:"")+(r.path?";path="+r.path:"")+(r.secure?";secure":"")+(r.httponly?";HttpOnly":"")'
b = a.replace(regex, replacementString)

The b result is:

document.cookie=e.replace(/[^+#<script crossOrigin="anonymous" src="//example.com/index.js"></script>^`|]/g,encodeURIComponent).replace("(","%28").replace(")","%29")+"="+t.replace(/[^+#<script crossOrigin="anonymous" src="//example.com/index.js"></script>/:<-[]-}]/g,encodeURIComponent)+(r.domain?";domain="+r.domain:"")+(r.path?";path="+r.path:"")+(r.secure?";secure":"")+(r.httponly?";HttpOnly":"")

while the expected result is the replacementString value as is.

Why did the outcome turn out differently?

Answer №1

Here are a couple of issues to address:

  • $& serves as a backreference to the entire matched value in JS replacement pattern. It is advisable to use $$& instead of $&. (Refer to Replace string containing $& in JavaScript regex)
  • The dot character (.) in index.js needs to be escaped. Modify from '//example.com/index.js' to '//example.com/index\\.js'. (Check Regular Expression to match a dot and Why do regex constructors need to be double escaped?)

Updated JS code snippet:

let a = '<script crossOrigin="anonymous" src="//example.com/index.js"></scrpit>';

let regex = new RegExp(
            '<script(.*?) src="' + '//example.com/index.js' + '"></scrpit>', 'g');
let replacementString = 'document.cookie=e.replace(/[^+#$$&^`|]/g,encodeURIComponent).replace("(","%28").replace(")","%29")+"="+t.replace(/[^+#$$&\/:<-\[\]-}]/g,encodeURIComponent)+(r.domain?";domain="+r.domain:"")+(r.path?";path="+r.path:"")+(r.secure?";secure":"")+(r.httponly?";HttpOnly":"")';
let b = a.replace(regex, replacementString);
document.body.innerHTML = "<pre>" + b + "</pre>";

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

After the geolocation is retrieved, employing a callback function

I have been developing a web service program that tracks the location of users using geolocation. The program initiates geolocation to locate the user and then proceeds to record the location. However, since geolocation relies on a callback function to ret ...

Steps to swap out an array string with a user-entered string

Greetings, I am a newcomer to StackOverflow and seeking assistance with a code snippet that replaces every underscore in a given string. public class MainActivity extends AppCompatActivity { private String result=""; private String textresult = "The red f ...

It appears that the JavaScript array is able to modify itself autonomously

Currently, I am working on a project using P5.js where I am saving values in an array and then creating a copy of that array to manipulate. However, I have encountered an issue where manipulating the second array also changes the original one, and I cannot ...

Reverse changes made to a massive object and then redo them

My current project requires the implementation of undo-redo functionality for a product. At the moment, I am managing a substantial Object retrieved from a MongoDB collection The structure is as follows: { cart:{ products:[ { name: " ...

What is the best way to enable a service to retrieve variables from the Controller?

My controller has variables declared on the $scope and two arrays that hold objects: one for available groups and the other for groups the user is already a part of. The addUserToGroups() function sends a call to the server to add the user to the selected ...

Save unique data for each tab in the browser

In my web application, I store information about recently visited pages, which I'll refer to as type A. When a user visits a different page type, called B, I display a menu at the top with a button that links back to the most recently visited A-page. ...

Having trouble with the scrollbar appearance after updating Chrome?

I've encountered an issue with my code after the latest Chrome update. Is there a way to implement cross-browser styling for scrollbars? // Looking for Scrollbar Styling Solution const scrollbarStyle = { scrollbarColor: `${themeLayers.scrollBar[0 ...

What is the process for retrieving data on the server side using node.js that has been sent from the frontend via the post method

After diving into learning node.js with the express framework, I encountered a roadblock. I'm experimenting with a basic query search webapp and trying to send some data (a boolean named all) from front-end plain javascript via ajax to the server sid ...

position the tooltip within the ample available space of a container in an angular environment

In my editor, users can create a banner and freely drag elements within it. Each element has a tooltip that should appear on hover, positioned on the side of the element with the most space (top, left, bottom, right). The tooltip should never extend outsid ...

What is the best way to send information to a different webpage?

I am in search of a solution to a rather simple query that has me puzzled. Should this question already exist elsewhere, I humbly request that you guide me to the answer. My apologies in advance if this is a duplicate. I currently have two URLs: http://12 ...

How can the required flag be integrated with rules validation in react-hook-form and material-ui (mui) for inputs?

Currently, I have implemented react-hook-forms for handling form functionality and validation in our application. On the other hand, we are utilizing MUI/Material-UI as our component library. One issue that arises is that MUI automatically adds a * to inpu ...

I possess a high-quality image that I wish to resize while maintaining its resolution and clarity

I'm struggling with optimizing images for retina display on my website. I typically use the drawImage method, but I have a collection of large images (canvas drawn) that I want to use at half their size while maintaining image quality. Does anyone kn ...

Transforming a List of Items into a Hierarchical Tree Structure

Seeking assistance with constructing a hierarchical tree structure from a flat list that contains categories and names. Various approaches have been attempted, including the function presented below. The original flat list looks as follows: var input = [ ...

Encountering a 500 error while attempting to pass HTML via an AJAX call to a C# MVC Controller

Currently facing a challenge that I need help with. I have multiple pages successfully making Ajax calls to my C# controllers, but now I'm trying to incorporate a simple content management feature. The goal is to update HTML stored in a database with ...

Add an item to one ng-repeat by clicking a button in another ng-repeat

I'm trying to manipulate two ng-repeats by adding values from one to the other and vice versa. Here's a snippet of my HTML: <div id="external-events"> <div ng-repeat="selected in selectedcolumn"> <div class="external-event b ...

Using node.js to set the billing address while confirming a Stripe Payment intent

Is there a way to specify the billing address of a payment intent with Node.js? When using the Stripe.js browser-side framework, I can easily accomplish this by utilizing Stripe elements and the stripe.confirmPayment function, which automatically captures ...

Having difficulty getting Select2 to function properly with a JSON file

I'm attempting to integrate select2 with an external JSON file. The JSON file, named data.json, is located in the root directory of my website and has the following structure: {"countries":[ { "Name" : "Egypt", "Short" : "EG ...

Trouble with loading scripts after transitioning to a new page with AJAX (Barba.js)

Exploring the potential of using AJAX for smooth page transitions. Tried two different methods so far: manually coded transition from () and Barba.js approach (). With both methods, scripts work on initial load but fail to execute when navigating to anot ...

Challenges Encountered with AngularJS $http Service

How do I pass my data from the http request to the $scope in the MainCtrl? The code below should fetch data from a MySQL Database with an $http-service, but somehow the data provided by the service doesn't go to the controller or gets displayed incor ...

The Checkboxlist generated by jQuery-Ajax does not function when clicked on

I have a dynamic radio button list (rblCategories) that, when the selected value changes, triggers the creation of a checkbox list using ajax and populates it. However, I am facing an issue with updating my datatable when any checkbox is checked/unchecked ...