繁体   English   中英

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

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

这是我的绳子。

var id = "timesheet_entries_attributes_0_entry_overtimes_attributes_0_code_id"

问题是我想用另一个数字替换最后一个零。

零的位置总是变化的。 但是字符串中只有两个零。 他们不能在一起。

如 :

var num =“ 2”; (“ timesheet_entries_attributes_0_entry_overtimes_attributes_0_code_id”)。replace(/ \\ d /,num);

但它总是替换第一个零。

SoS!

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

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

只是另一种解决方法:

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

演示

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