How to perform global substring replacement in Javascript while applying a specific rule?

Is there a way to create a function that can replace substrings in a large string based on specific rules?

For instance, I need every digit associated with pageX in the string to increase by 10.

function replace(str, increment){}

Using

replace("pageX : 100, pageY: 200,......pageX : 120...", 10)
would result in
"pageX : 110, pageY: 200,......pageX : 130..."

I am aware of methods like

string.replace(/pageX:/g,someStr)
for simple replacements, but how can I apply specific rules to each replacement?

Answer №1

Have you considered utilizing the replace function callback for this task:

var text = "pageX : 100, pageY: 200,......pageX : 120...";
text = text.replace(/(\d+)/g, function(match, digits) {
    return (+digits + 10);
});
console.log(text);

See it in action here: http://jsfiddle.net/ytptN/

Answer №2

Utilize Regexp in JavaScript to identify all numbers by using the pattern \d+ and then leverage the String.replace method to replace them accordingly with a function call. You can manipulate or multiply the matched numbers within the function before inserting them back into the text.

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

The click event does not seem to be functioning properly within a contenteditable div

Incorporating a delete button within the div would allow users to delete it upon clicking. However, there are currently two issues: (1) The alignment of the delete button with the text in the div is not accurate. (2) The click event for the button is not ...

Tips for detecting the existence of scrollbar on a webpage and retrieving its coordinates

I am working on a web page where I need to dynamically retrieve the scroll coordinates of the page. If a page has multiple scrolls, I should be able to get the respective scroll coordinates for each. The functionality needs to adjust based on the specifi ...

What is the most reliable database for handling daily data?

Currently, I am involved in a project that involves monitoring daily data for approximately 30 fictional companies. Each company is associated with a name, rank, and balance. I aim to track the rank and balance by storing the data daily. My main query re ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

AngularJS $http get isn't functioning properly, but surprisingly $.ajax works perfectly

Recently delving into the world of AngularJS, I am facing a hurdle with $http functionality. In my factory setup below: app.factory('employeeFactory', function ($http) { var factory = {}; // Retrieving data from controller var emplo ...

Ways to design a vertical tab using CSS and JavaScript

I am currently working on creating a Vertical tab element using CSS and jQuery. However, I am facing an issue where I need to display the content of the first tab upon page load. I have tried using the following line of code but it does not seem to be work ...

There was an unhandled rejection error stating: "TypeError - Unable to access property 'push' as it is undefined"

I am encountering an issue while trying to create a function that returns all indexes of an array. I'm not sure what mistake I might be making, as I keep getting an error stating that push cannot be used due to an undefined value. Here's the cod ...

The Integration of Google Books API with Ajax Technology

When a user enters an ISBN number in the search box, it triggers a display of information from the Google Books API within a div. This information is fetched from a JSON file in the standard format and includes details like title, subtitle, author, and des ...

How to remove checkbox border using HTML, JavaScript, and CSS

Is it possible to remove the square border from a checkbox in HTML? ...

Using THREE.js to cast rays from a secondary camera onto the scene

I've been attempting to raycast the mouse from my camera in order to trigger hover and click events on meshes within my scene. The issue I'm facing is that my camera is currently a child object of another mesh (to facilitate easier camera moveme ...

Having trouble with the npm Twitter API functionality?

I'm attempting to execute a simple stream using an example code snippet. Here is the code I am working with: var twit = require('twitter'); var twitter = new twit({ consumer_key: '[KEY]', consumer_secret: &ap ...

When attempting to make my styles responsive, I found that they broke due to duplicate classes on the landing page I was creating with next.js and styled components

Something strange is unfolding, and I find myself confused about the overall situation. Let me try to explain it the best I can. On my landing page, there are three different components: const Home = () => { return ( <> <Head> ...

Vue.js bootstrap-vue input number has a unique MaxLength feature that sets the

Is there a way to limit the input length for an input field from bootstrap-vue? I tried using maxLength, but it seems that it's not supported based on their documentation. If I remove type="number", the limitation works, but then it won't restric ...

Tips on implementing two ng-repeat directives within a specific element

Inside a JSON file, there is an array that needs to be iterated within <td> tags. The functionality entails creating a table based on user input, which includes the number of rows, input columns, and output columns provided by the user. Three arrays ...

The @output decorator in Angular5 enables communication between child and

Hello fellow learners, I am currently diving into the world of Angular and recently stumbled upon the @output decorators in angular. Despite my best efforts to research the topic, I find myself struggling to fully grasp this concept. Here's a snippet ...

Choosing a specific category to display in a list format with a load more button for easier navigation

Things were supposed to be straightforward, but unexpected behaviors are popping up all over the place! I have a structured list like this XHTML <ul class = "query-list"> <li class="query"> something </li> <li class="query" ...

Issue: The system is unable to locate the "moduleIntro.js" module while executing the "http" command

I recently embarked on a journey to learn Node.js and decided to experiment with the 'http' module. Here is a snippet of the code I tried to run: var http = require('http'); http.createServer(function (req, res) { res.write('H ...

Sending string variable from Perl CGI script to HTML frontend

Having just begun experimenting with AJAX, I'm encountering difficulties in passing variables back to my HTML script. In this setup, I'm using a combination of a XAMPP webserver, JavaScript, and jQuery for the HTML script, along with a Perl cgi ...

Blunder! Error code EINVALIDTAGNAME encountered while trying to install a package

I'm encountering an issue while trying to add a new package to my React application. The error I'm receiving is: $ npm install xlsx npm ERR! code EINVALIDTAGNAME npm ERR! Invalid tag name "react-scripts start": Tags may not have any characters th ...