Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace only the Second number from a string

How do i replace the second number from a string only?

Actual sting:
messages_0_items_0_data_0

Required Results:
messages_0_items_1_data_0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var new_index = 1;
this_input.attr('id', this_input.attr('id').replace(/[0-9]+(?!.*[0-9])/, new_index ));

the above code is changing the last number rather than the second number like follwoing:

Not Good:
messages_0_items_0_data_1

>Solution :

You could capture just before the second number in group 1, and then match the second number to be replaced.

^(\D*\d+\D+)\d+

See a regex demo.

const s = `messages_0_items_0_data_0
messages[0][items][0][data][0]`;
const regex = /^(\D*\d+\D+)\d+/gm;
console.log(s.replace(regex, (m, g1) => `${g1}1`));

Or with a callback function to make it more clear using group 1:

s.replace(regex, (m, g1) => `${g1}1`)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading