mozicid
mozicid

Reputation: 55

Getting number of repetitions in regex in JavaScript

This is kinda a follow-up question from this, in which a solution was provided for Notepad++ but unsuitable for JavaScript.

Let's say I have some random text:

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

Now I want to replace each digit that appear after a newline with X, to achieve this end-result:

`aaaaaaaaaa
 Xaaaa8aaaa
 XXXXaaaaaa
 a1aaaaaaaa
 XXXaaaaaaa`

The solution provided for Notepad++ cannot be used here because the \G anchor is not available in JavaScript so 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?

Upvotes: 3

Views: 57

Answers (1)

Ram
Ram

Reputation: 144679

One option is:

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

Upvotes: 1

Related Questions