简体   繁体   English

如何使用javascript的正则表达式匹配第二个数字?

[英]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"; var num =“ 2”; ("timesheet_entries_attributes_0_entry_overtimes_attributes_0_code_id").replace(/\\d/,num); (“ timesheet_entries_attributes_0_entry_overtimes_attributes_0_code_id”)。replace(/ \\ d /,num);

but it always replace the first zero. 但它总是替换第一个零。

SoS! SoS!

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

此版本替换字符串中的LAST数字。

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 演示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM