Home > Back-end >  Modify numbers in large string
Modify numbers in large string

Time:01-10

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

CodePudding user response:

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)
});

CodePudding user response:

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));

  • Related