3

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

3
  • 3
    Add + after [0-9]. Commented Feb 5, 2019 at 19:48
  • 1
    You should read a regexp tutorial, this is one of the most basic patterns. Commented Feb 5, 2019 at 19:48
  • If you did substantially edit your question or answers did not work for you, please comment and keep community updated. Commented Feb 6, 2019 at 10:15

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

It will match any number of number. more precisely it should be atleast one
@Code Maniac what you mean?
+ stands for one or more. any can be zero also
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.