Search code examples
javascriptregexregexp-replace

How to do Typescript regex replace and extract value in the same time?


I'd like to change path = 'a.0.b.c.e.f.11.d.20' to 'a[0].b.c.e.f[11].d[20]'

I was thinking to use something like : replace(/\.\d+/g , '.[${d+}]');

But this is not working. How can I replace the .number with with value .[number]?


Solution

  • After matching a period, capture digits in a group, then replace with those digits in brackets using the capture group:

    console.log(
      'a.0.b.c.e.f.11.d.20'
        .replace(/.(\d+)/g, '[$1]')
    );