Mask only 9 digit number

murali from

I want to mask only 9 digit number in string. If string contains less than 9 or greater than 9 it shouldn't mask that number.

My code:

var str = 'My Business phone number is 1234567890 and my personal number is 123456789';
    
var rgx1 = /\d{9}/;
    
var find1 = rgx1.test(str);
    
if(find1){
     var str1 = str.replace(/\d{5}/, '#####');
     console.log(str1);
}

Result: My Business phone number is 1234567890 and my personal number is #####6789

But this code returns true if it has more than 9 digit number and also if string contains 9 and 10 digit number it should mask only that particulr 9 digit number.

javascript regex

Answers

answered 6 days ago The fourth bird #1

In your code, the test part matches if the string contains 9 consecutive digits which also matches if there are 10 digits. Then you replace 5 digits of the the first occurrence (which is 1234567890) with #####

What you might do is omit the var find1 = rgx1.test(str); part and use \b\d{9}\b which uses a word boundary \b to make sure it is not part of a longer match.

You could use replace with a callback function. In the callback function replace the first 5 digits with #####. To replace all matches instead of only the first you could add the /g modifier.

var str = 'My Business phone number is 1234567890 and my personal number is 123456789';
var str1 = str.replace(/\b\d{9}\b/g, function(match) {
  return match.replace(/\d{5}/, '#####');
});
console.log(str1);

answered 6 days ago AnilRedshift #2

You can do this in one regex, to capture 9 digit numbers, surrounded by word breaks:

const test = "nine digits: 123456789 and ten digits 0123456789"
console.log(test.replace(/\b\d{5}(\d{4})\b/, '#####$1'))

The regex looks for: a word break, followed by 5 digits, followed by 4 digits, followed by a word break. The last four digits are captured so they can be referenced by $1 in the replace

This is a preferred solution because you don't have to worry about any edge cases such that you have part of your string match your outer regex, but a different part of the string match your inner regex.