如何在Javascript中替换正则表达式子字符串匹配?

如何在Javascript中替换正则表达式子字符串匹配?

问题描述:

var str   = 'asd-0.testing';
var regex = /asd-(\d)\.\w+/;

str.replace(regex, 1);

用 str code> 1 。我希望它替换匹配的子字符串而不是整个字符串。这可以在Javascript中使用吗?

That replaces the entire string str with 1. I want it to replace the matched substring instead of the whole string. Is this possible in Javascript?

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);

或者,如果您确定字符串中没有任何其他数字:

Or if you're sure there won't be any other digits in the string:

var str   = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);