dave
dave

Reputation: 7867

How can I replace a regex substring match 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?

Upvotes: 145

Views: 221301

Answers (6)

Amarghosh
Amarghosh

Reputation: 59461

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

Upvotes: 165

Youp Bernoulli
Youp Bernoulli

Reputation: 5655

A One-Liner based on @Greg7000's answer 👍🏼 which uses a replacer method:

'asd-0.testing'
  .replace(
    /(asd-)\d(\.\w+)/,
    (match: string, p1: string, p2: string) => { 
      return `${p1}1${p2}`; 
    });

Upvotes: 4

Greg7000
Greg7000

Reputation: 425

Personally, I like the liberty provided by the replacer technique (Search for 'Specifying a function as the replacement' section). This is also simplier to debug in details.

function replacer(match, p1, p2, offset, string) {
    console.log('match = ' + match);
    console.log('p1 = ' + p1);
    console.log('p2 = ' + p2);
    console.log('offset = ' + offset);
    console.log('string = ' + string);
    custom_op = p1 + 1 + p2;

    return custom_op;
}

var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

matches = str.match(regex)

res = str.replace(regex, replacer);
console.log(res);

// ----OUTPUT----
// match = asd-0.testing
// p1 = asd-
// p2 = .testing
// offset = 0
// string = asd-0.testing
// asd-1.testing

NOTE: To ease the identification of regex groups, consider using https://regex101.com/

Upvotes: 1

Lantanios
Lantanios

Reputation: 89

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

Upvotes: 6

Félix Saparelli
Félix Saparelli

Reputation: 8749

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]}`;

Upvotes: 31

user180100
user180100

Reputation:

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

Upvotes: 63

Related Questions