How can I replace a regex substring match in Javascript? How can I replace a regex substring match in Javascript? javascript javascript

How can I replace a regex substring match 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);


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

Edit: adaptation regarding the comment


I would get the part before and after what you want to replace and put them either side.

Like:

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]}`;