How can I replace a regex substring match in Javascript?

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


str.replace(regex, 1);

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?

201373 次浏览

我会得到你想要替换的零件,并把它们放在任何一边。

比如:

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


var matches = str.match(regex);


var result = matches[1] + "1" + matches[2];


// With ES6:
var result = `${matches[1]}1${matches[2]}`;

使用 str.replace(regex, $1);:

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


if (str.match(regex)) {
str = str.replace(regex, "$1" + "1" + "$2");
}

编辑: 关于评论的改编

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

或者如果你确定字符串中没有其他数字:

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

我认为实现目标最简单的方法是:

var str   = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);