0

this is my string.

var id = "timesheet_entries_attributes_0_entry_overtimes_attributes_0_code_id"

question is I want to replace the last zero with another number.

the zero's position is always change. But there are only two zeros in the string. And they can't be together.

such as :

var num = "2"; ("timesheet_entries_attributes_0_entry_overtimes_attributes_0_code_id").replace(/\d/,num);

but it always replace the first zero.

SoS!

0

3 Answers 3

1
id.replace (/(\d+)(?=\D+$)/, '2')

This version replaces the LAST number in the string.

Sign up to request clarification or add additional context in comments.

Comments

0
var id = "timesheet_entries_attributes_0_entry_overtimes_attributes_0_code_id";
var num_replace = 5;
id = id.replace(/(\d+.*)\d+/, "$1"+num_replace);

Comments

0

Just a different way to solve:

var id = "timesheet_entries_attributes_0_entry_overtimes_attributes_0_code_id",
    matchIndex = 1,
    replace = 300,
    count = -1;

id = id.replace(/\d+/g, function(number) {
    count++;
    return (count == matchIndex) ? replace : number;
});

demo

1 Comment

And how to replace the second number?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.