How can I replace a regex substring match in Javascript?

JavascriptRegexReplaceSubstring

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - 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);

Solution 2 - Javascript

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

Solution 3 - 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];

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

Solution 4 - Javascript

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`);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondaveView Question on Stackoverflow
Solution 1 - JavascriptAmarghoshView Answer on Stackoverflow
Solution 2 - Javascriptuser180100View Answer on Stackoverflow
Solution 3 - JavascriptFélix SaparelliView Answer on Stackoverflow
Solution 4 - JavascriptLantaniosView Answer on Stackoverflow