How can I replace a regex substring match in Javascript?
187,784
Solution 1
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);
Solution 2
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]}`;
Solution 3
I think the simplest way to achieve your goal is this:
var str = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);
Author by
dave
Updated on March 10, 2020Comments
-
dave over 4 years
var str = 'asd-0.testing'; var regex = /asd-(\d)\.\w+/; str.replace(regex, 1);
That replaces the entire string
str
with1
. I want it to replace the matched substring instead of the whole string. Is this possible in Javascript? -
eduncan911 about 10 years+1 I personally like having the collection of matches to frack with.
-
Travis J about 9 yearsI agree, having the matched set available is more readable in my opinion.
-
Ivan Rave about 9 yearsor using function: 'asd-0.testing'.replace(/(asd-)\d(\.\w+)/, function(mystring, arg1, arg2){return arg1 + 'mynumber' + arg2})
-
Martin Massera almost 8 yearsis there any answer where you DONT know the structure of the regex? here you are basically creating a new regex with two matches
-
Bas Slagter almost 5 yearsIt is good to know that you need braces () around the part you want as $1, $2 etc.