views:

48

answers:

3
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?

A: 

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];
passcod
+1  A: 

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

RC
I want to replace the substring with '1' not the entire string with the substring
dave
+1  A: 
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);
Amarghosh