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?
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?
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];
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
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);