George George
George George

Reputation: 601

Javascript regex to replace numbers in sequence

I am trying to replace numbers in string with the character "X" which works pretty good by replacing every individual number.

This the code:

 let htmlStr = initialString.replace(/[0-9]/g, "X");

So in a case scenario that initialString = "p3d8" the output would be "pXdX"

The aim is to replace a sequence of numbers with a single "X" and not every number (in the sequence) individually. For example:

If initialString = "p348" , with the above code, the output would be "pXXX". How can I make it "pX" - set an "X" for the whole numbers sequence.

Is that doable through regex?

Any help would be welcome

Upvotes: 3

Views: 2028

Answers (3)

jo_va
jo_va

Reputation: 13973

Use the \d token to match any digits combined with + to match one or more. Ending the regex with g, the global modifier, will make the regex look for all matches and not stop on the first match.

Here is a good online tool to work with regex.

const maskNumbers = str => str.replace(/\d+/g, 'X');

console.log(maskNumbers('abc123def4gh56'));

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36584

You can use + after [0-9] It will match any number(not 0) of number. Check Quantifiers. for more info

let initialString = "p345";
let htmlStr = initialString.replace(/[0-9]+/g, "X");
console.log(htmlStr);

Upvotes: 3

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92517

Try

let htmlStr = "p348".replace(/[0-9]+/g, "X");
let htmlStr2 = "p348ad3344ddds".replace(/[0-9]+/g, "X");

let htmlStr3 = "p348abc64d".replace(/\d+/g, "X");

console.log("p348           =>",htmlStr);
console.log("p348ad3344ddds =>", htmlStr2);
console.log("p348abc64d     =>", htmlStr3);

In regexp the \d is equivalent to [0-9], the plus + means that we match at least one digit (so we match whole consecutive digits sequence). More info here or regexp mechanism movie here.

Upvotes: 8

Related Questions