Home > Net >  Replace only the Second number from a string
Replace only the Second number from a string

Time:03-21

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

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

CodePudding user response:

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

  • Related