How can I replace a regex substring match in Javascript?

dave picture dave · Aug 30, 2010 · Viewed 166.8k times · Source
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?

Answer

Amarghosh picture Amarghosh · Aug 30, 2010
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);