Having difficulty using JavaScript regex to replace the middle of content?

I am working with a text

name[one][1][two][45][text]

Through this pattern, I am able to extract the number "45"

/(.*?)rows\]\[([0-9]*)(.*)/;

Now, my challenge is how can I change the only 45 to a different digit? Using the same pattern and replace method replaces the entire previous word. Here is the code snippet:

var name = "name[one][1][two][45][text]";
var pattern = /(.*?)two\]\[([0-9]*)(.*)/;
var number = name.match(pattern);
number = parseInt(number[2]);

var replacePattern = /(.*?)two\]\[([0-9]*)/;
var newName = name.replace(replacePattern, parseInt(number + 2));
console.log(newName);

Unfortunately, the output is 47][text]

Answer №1

Is there a way to substitute the lone 45 with any different number?

You have the option to utilize the replace function with matching groups:

For instance — I swapped out the 45 with 7 here:

   "name[one][1][two][45][text]".replace(/(.*?)(two\]\[)([0-9]*)(.*)/,function (a,b,c,d,e){
        // implement your desired replacement
        return b+c+'7'+e;
    })

Output:

"name[one][3][two][7][text]"

Take note that I've included () to encompass other sections that can be added later.

Edit: in relation to your specific example (+=2) : this method can be used:

return b+c+(parseInt(d)+2)+e; -- for your exact scenario

Answer №2

In the event that you can guarantee there will only be 2 numbers present, utilize the following regular expression pattern:

([0-9]+)(?!.*?\d)

Take a look at the demo for reference.

https://regex101.com/r/pL4kQ8/1

Answer №3

If you want to achieve this, follow these steps:

let myVar = "variable[test][1][key][23][string]";
// regex pattern to detect 2 or more digits within square brackets
let myPattern = /\[([\d]{2,})\]/;
console.log(myVar.replace(myPattern,"[47]");)

Answer №4

When using String.replace in JavaScript, you have the option to pass a function as the second argument. This function will be called for each regex match found in the string, allowing you to perform additional calculations or manipulations within that function.
By adjusting the capturing groups in the regex pattern slightly, you can achieve different outcomes. Here is an example:

name.replace(
    /((?:.*?)two\]\[)([0-9]*)(.*)/g, 
    function(match, group1, group2, group3){
        //Adding 2 to the number captured in the regex
        return group1 + (parseInt(group2) + 2) + group3;
    }
)
> "name[one][2][two][47][text]"

Check out this Regex demo

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

Completed processing graphical event layer

I am utilizing the Google Maps API v3 to build a map with multiple layers that are loaded upon user request. The layers are loaded in Geojson format using the following code: function getgeojson(json) { proplayer = new google.maps ...

Encountering the error message "Unable to locate module '.nextserverpages-manifest.json'" while attempting to include `babel.config.js` in a Next.js application

During the process of setting up testing for my current next app, we incorporated some new dependencies including jest, babel-jest, @babel/preset-env, @babel/preset-react, and react-test-renderer. We also created a babel.config.js file to configure Babel s ...

An error occured when attempting to read the 'status' property of an undefined value in node.js, express.js, and mysql

I recently started working with node.js and encountered a challenge in fetching data from mysql and sending it to an API response. Below is my setup: db.js: var mysql = require('mysql2'); var util = require('util') const pool = mysql ...

Update the existing code to incorporate icons into the column formatting

I'm seeking assistance from someone knowledgeable in JSON or coding as this is not my area of expertise. In my sharepoint online list, I have customized the display to show different colors based on the text content in each item. Now, I am looking to ...

Every time I attempt to submit the login form on the Ionic and Angular page, instead of capturing the values of the form group, the page simply refreshes

Struggling with submitting the login form in Ionic and Angular? When attempting to submit, the page reloads instead of capturing the form group values. I am utilizing angular reactive forms and form builder within the ionic framework. Need assistance in id ...

When modifying v-model directly in a Vue instance, the Vuetify component on the screen may not update its displayed value

Within my Vue component example (utilizing Vue 2 and Vuetify 1), I have implemented an input field for user data entry. However, I am looking to programmatically alter the input field's data to a specific value. For instance, in this scenario, I aim ...

Determining the character encoding of a JavaScript source code file

For my German users, I want to display a status message with umlauts (ä/ü/ö) directly in the source file instead of requiring an extra download for messages. However, I'm having trouble defining the encoding for a JS source file. Is there a way si ...

The creation of a MozillaBrowserBot object has encountered an error

Attempting to access the MozillaBrowserBot object in Mozilla JS has been unsuccessful for me. The code I utilized is shown below: function externalApplication(){ var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Com ...

Challenges Encountered when Making Multiple API Requests

I've encountered a puzzling issue with an ngrx effect I developed to fetch data from multiple API calls. Strangely, while some calls return data successfully, others are returning null for no apparent reason. Effect: @Effect() loadMoveList$: Obse ...

Showcase a Pair of Files Next to Eachother using HTML

I am a beginner with HTML and I am trying to accomplish a seemingly simple task. I have searched for similar questions and attempted the solutions provided, but none have worked for me. My goal is to have two documents displayed side by side on a web page ...

Label alignment in one line with responsive checkbox

Could someone assist me with adjusting the alignment of this checkbox when resizing the window for mobile view? The label text is breaking into a new line while the checkbox remains in its original position. How can I make the checkbox align closer to its ...

SQL inputs with information that updates automatically / autofill SQL input boxes

Is it feasible to create a webpage that can connect to an SQL database, retrieve information from a table, and display it in a text box based on the input provided in another text box? Essentially, I am looking for a way to enable autofill functionality. I ...

Using Javascript, delete all chosen HTML elements containing innerText

Looking to extract certain HTML tags from a block of code in TextArea1 and display the modified output in TextArea2 upon clicking a button. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8&quo ...

What are the best methods for ensuring a website maintains consistent visibility across all different screen sizes?

Recently, I created a website tailored for a viewport size of 1366px by 768px. My goal is to maintain the same design regardless of the browser window size without implementing responsive design techniques. For instance: When viewing the website on a 360 ...

Retrieve information from a text

I retrieved this data as a string from a webpage using jQuery and need help parsing it. When I attempted to use jQuery.parseJSON, I encountered the error Uncaught SyntaxError: Unexpected token n. The specific values I am looking for are "surl" and "imgur ...

Having trouble with Angular 2's Output/emit() function not functioning properly

Struggling to understand why I am unable to send or receive some data. The toggleNavigation() function is triggering, but unsure if the .emit() method is actually functioning as intended. My end goal is to collapse and expand the navigation menu, but for ...

Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows: [ {"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","tr ...

Utilizing Bootstrap 5: Executing JavaScript exclusively upon successful form validation

I've created a form with multiple input fields that are being validated using Bootstrap 5 validation. <form class="needs-validation asset-test" action="{{ url_for('asset_test') }}" method="post" novalidate> ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

Passing a JSON file name as an argument to a command line in Node.js

When I run app.js using the command node app.js, it will execute const inputData = require('./input.json'); Now, my question is - can I pass the file name as an argument to const inputData = require('./file.json'); directly from the co ...