Reputation: 1099
I'm trying to modify certain numbers inside a large string, which start with an #.
So for example I have this String:
var text = "#41 = AXIS2_PLACEMENT_3D ( 'NONE', #3200, #1543, #6232 ) ;
#42 = EDGE_CURVE ( 'NONE', #180, #933, #1234, .T. ) ;"
Then I want to add a fixed number to every number after an "#" e.g. add 100 to every number to get this:
text = "#141 = AXIS2_PLACEMENT_3D ( 'NONE', #3300, #1643, #6332 ) ;
#142 = EDGE_CURVE ( 'NONE', #280, #1033, #1334, .T. ) ;"
I got this far with regex:
const offset = 100;
const matchingExpression = /\#(\d+)/ig;
text = text.replaceAll(matchingExpression, "#" + //old value + offset);
I now can replace all numbers that start with an "#". But how do I get the old values?
I'm not very familiar with regex and don't know if this approach is the way to go. Hope you can help me.
Thanks in regard
Upvotes: 2
Views: 51
Reputation: 206668
Use the second argument (function callback) of the String.prototype.replace method:
const add100 = (text) => text.replace(/#(\d+)/gm, (m, n) => `#${+n + 100}`);
const text = `#41 = AXIS2_PLACEMENT_3D ( 'NONE', #3200, #1543, #6232 ) ;
#42 = EDGE_CURVE ( 'NONE', #180, #933, #1234, .T. ) ;`;
console.log(add100(text));
Upvotes: 1
Reputation: 7277
You can use String.replace
like this:
const offset = 100;
const matchingExpression = /\#(\d+)/ig;
text = text.replace(matchingExpression, function(match) {
return "#" + (parseInt(match.slice(1)) + offset)
});
Upvotes: 0