fred
fred

Reputation: 3

how to use javascript's regex to match the second number?

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

Answers (3)

HBP
HBP

Reputation: 16033

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

This version replaces the LAST number in the string.

Upvotes: 1

Ricardo Lohmann
Ricardo Lohmann

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

demo

Upvotes: 0

xdazz
xdazz

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

Related Questions