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`);
Share:
187,784
dave
Author by

dave

Updated on March 10, 2020

Comments

  • dave
    dave over 4 years
    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?

  • eduncan911
    eduncan911 about 10 years
    +1 I personally like having the collection of matches to frack with.
  • Travis J
    Travis J about 9 years
    I agree, having the matched set available is more readable in my opinion.
  • Ivan Rave
    Ivan Rave about 9 years
    or using function: 'asd-0.testing'.replace(/(asd-)\d(\.\w+)/, function(mystring, arg1, arg2){return arg1 + 'mynumber' + arg2})
  • Martin Massera
    Martin Massera almost 8 years
    is 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
    Bas Slagter almost 5 years
    It is good to know that you need braces () around the part you want as $1, $2 etc.