Switch out regex with an equal number of characters

I am looking for a way to replace specific content using a regex with the same number of characters but replacing them with a character of my choice.

For instance:

content: "abcdefghi*!?\"asd";

should be transformed into:

content: "-----------------";

This is the regex I am using:

new RegExp("('|\").*('|\")", "gm")

Despite following advice from this answer on StackOverflow, my attempt is not successful:

source_text_safe = source_text.replace(new RegExp("('|\").*('|\")", "gm"), function ($0, $1, $2, $3) {
            return $1 + (new Array($2.length + 1).join("-")) + $3;
        });

When applied to this input:

::selected {
    color: purple
}
a {
    color: purple
}
a:hover {
    color: purple
}
a {
    color: purple
}
a:not("foobar\";{}omg") {
    content: 'example\';{} text';
    content: "example\";}{ text"
}
a {
    color: purple
}

The output obtained is not as expected, indicating an issue with the current implementation.

Interestingly, when replacing the content with null using the same regex, it works perfectly fine, suggesting that the problem might lie elsewhere.

Any suggestions or guidance would be greatly appreciated!

Answer №1

In order for the replacement function to work correctly, it is essential to have three capturing groups within the regular expression. If there are only two groups present, then the unexpected result experienced will be due to $3 retrieving the offset of the match. For more information, you can refer to the Mozilla JS reference on Specifying a function as a parameter.

To resolve this issue, consider using a regular expression like "('|\")(.*)('|\")", which contains 3 groups.

Answer №2

Alright, it looks like I've managed to figure it out...

source_text_safe = source_text.replace(new RegExp("('|\").*('|\")", "gm"), function ($0) {
    return (new Array($0.length + 1).join("-"));
});

I appreciate everyone's responses though.

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

Implementing a delay using setTimeOut function to execute an action upon user input

Take a look at this code snippet: $("#test").on("keyup", (e) => { if(e.target.value.length === 3) { setTimeout(() => { console.log("fired") }, 2000) } }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...

IE8 encountering issues with Jquery ajax() request

My current issue involves submitting data using ajax from forms with a class of ajax. This functionality works flawlessly in Firefox, Safari, and Chrome, but is unsuccessful in Internet Explorer. ajax: function() { $('form.ajax').live(&apo ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

A function that retrieves the empty values from an array and returns undefined if there

After undergoing a time-consuming process, the sample below shows that the array values are returned empty. function myFunction() { let myArray = []; let pastArray = [1, 2, 6, 7, 8, 1, 9, 6, 0] pastArray.forEach(item =>{ setTimeout(function(){ myA ...

Top method for transferring data between React components post retrieval from Axios Call

I am currently utilizing React JS in an application structured like the following diagram: This particular application fetches data from a Rest API (Node express) using Axios. The challenge I am facing is determining the most effective method for storing ...

There is an issue with the function of elem.autocomplete - it is not recognized

I'm new to Angular.JS and have been struggling for the past 6 hours. I've been working on reading data from an HTTP source and displaying it as an autocomplete feature on the view. Previously, the data was displayed in a select box, but I decide ...

What is the best way to submit a form using PHP to send an email, implement Ajax for seamless transitions, and display a message next to the form without any screen refresh?

Upon clicking the submit button, I am looking to achieve two things: (1) Sending the form data via email using PHP without refreshing the page. (2) Displaying a thank you message next to the form utilizing Ajax. Most of the functionality is in pl ...

Choose options from an array in AngularJS using the same ng-model for a dropdown menu

I have developed a cross-platform app using AngularJS, Monaca, and OnsenUI. Within the app, there is a large form with multiple drop-down select options. The majority of these options are Yes/No selections. To handle these Yes/No options, I've creat ...

Displaying Values/Marks in a Unique Order with Material-UI Slider Component

The default behavior of the Material-UI slider is to display marks/values in ascending order from min to max For instance, if you have a slider configured like this: const marks = [ { value: 1, label: '1' }, { value: 2, lab ...

Having trouble running the development environment with npm or pnpm due to permission problems

I encounter this issue when running the command without sudo, but everything works fine with elevated permissions. What could be causing this discrepancy? I've searched for similar questions on various platforms and encountered the same problem with b ...

Steps for accessing specific menu div on a new tab

I'm facing an issue with my one page website. Whenever I click on a menu item, it directs me to a specific div tag on the page. However, if I right-click on a menu item and select 'open in new tab', it opens the URL "www.mysite.com/#" instea ...

Struggling with navigating JSON data in JavaScript and facing difficulties sorting the array

I am currently facing the challenge of organizing data obtained from an API using JavaScript. JavaScript Code to Retrieve Data: function getResults() { var url = $.getJSON("http://api.api.com&leagues=SOCENGPRE&lang=en&format=jsonp&cal ...

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

display the HTML form when the page is clicked

Trying to implement an onclick method for selecting form types. I have multiple form types available - example here Clicking on one submenu should open up the desired form type directly below the menu How can I dynamically load a form based on the select ...

Unable to dynamically change the value of the submit button using angular.js

I'm facing an issue with setting the submit button value dynamically using Angular.js. The code I've written below explains my problem. <body ng-controller="MainCtrl"> <input type="submit" value="{{ !model ? 'reset' : mod ...

What is the best way to ensure that the content container's max-width for a split tier is the same as the width of a full-width tier?

My goal is to create a split tier on a webpage with a 60/40 layout. The size of this tier should be calculated based on the maximum width of the container above it. Using JavaScript and jQuery, I managed to derive the max-width value of the full-width-tier ...

Combine several dictionary values under a single dictionary key in JavaScript

I have a unique dictionary structure displayed below. My goal is to populate it with values in a specific way. It all begins here var animals = { flying : {}, underground : {}, aquatic : {}, desert : {} }; To illustrat ...

Prevent the Swiper slider from autoplaying while a video is being played, and automatically move to the next slide once the video is paused or

<div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <video-js id="6304418462001" class="overlayVideo" data-account= ...

Is there a Selenium regex specific to trademarks that can be used in

Just diving into the world of regex and selenium, I need to verify the presence of a text like this: © Negurici 2012. All rights reserved. Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="29474c4e5c5b404a40694e4448404507 ...

Error: Unable to locate npm package

I am currently working on an Angular application that was created using Grunt and relies on Bower and NPM. Recently, I attempted to install an npm module locally. The installation resulted in the files being stored in the main application directory under ...