Reputation: 3
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!
Upvotes: 0
Views: 841
Reputation: 16033
id.replace (/(\d+)(?=\D+$)/, '2')
This version replaces the LAST number in the string.
Upvotes: 1
Reputation: 26320
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;
});
Upvotes: 0
Reputation: 160833
var id = "timesheet_entries_attributes_0_entry_overtimes_attributes_0_code_id";
var num_replace = 5;
id = id.replace(/(\d+.*)\d+/, "$1"+num_replace);
Upvotes: 0