Getting the number of repetitions in a regular expression in JavaScript

This is sort of the next question out of this that provided a solution for Notepad ++ but not valid for JavaScript.

Let's say I have some random text:

let text = `aaaaaaaaaa
            5aaaa8aaaa
            4707aaaaaa
            a1aaaaaaaa
            923aaaaaaa`;

      

Now I want to replace every digit that appears after the new line with X

, to achieve this end result:

`aaaaaaaaaa
 Xaaaa8aaaa
 XXXXaaaaaa
 a1aaaaaaaa
 XXXaaaaaaa`

      

The solution intended for Notepad ++ cannot be used here, as the anchor is \G

not available in JavaScript and therefore text.replace(/(?:\G|^)\d/gm, 'X')

does not work.

Are there any alternatives to using \G

here, or any other ways to do this replacement in JavaScript?

+3


source to share


1 answer


One of the options:



text.replace(/\b(\d+)/g, m => 'X'.repeat(m.length))

      

+1


source







All Articles