Home > Mobile >  How can I mask the digits in a alphanumeric string when the count of digits reaches 10?
How can I mask the digits in a alphanumeric string when the count of digits reaches 10?

Time:10-01

I have an alphanumeric string, so I want to mask all the numbers in this string when the count of digits reaches 10. In this example, the digit count has reached the count of 10 two times irrespective of how many space, special character,s or digits are there


For ex:
string 1:- abc23 56 dfg %#34567fhgh0 1234567890 abc345
Output:-   abc** ** dfg %#*****fhgh* ********** abc345

It ignores the characters and mask the number when the digit length reaches 10. I want to do this with regex. How can I do that?

CodePudding user response:

You may use something like this:

if ((s.match(/\d/g) || []).length >= 10) {
    s = s.replace(/\d/g, '*');
}

This will count the number of digit matches. If there are 10 or more digits, it replaces each one with a '*' character. If you want to only replace the digits if the string contains at least one set of 10 consecutive digits, see the end of the answer.

Here's a complete example:

var arr = ['abc23 56 dfg %#34567fhgh0 1234567890 abc345', 'abc123def'];
for (var i = 0; i < arr.length; i  ) {
    let s = arr[i];
    if ((s.match(/\d/g) || []).length >= 10) {
        s = s.replace(/\d/g, '*');
        arr[i] = s;
    }
    console.log(s);
}

Output:

abc** ** dfg %#*****fhgh* ********** abc***
abc123def

If you want the condition to be for 10 consecutive digits, use the following instead:

if (/\d{10}/g.test(s)) {
    s = s.replace(/\d/g, '*');
}

CodePudding user response:

You could split() the string into an array, check the length of the string, if it is over 10, then map the mask character where the number was using splice and its key along with Number and isNan.

var str = 'abc23 56 dfg %#34567fhgh0 1234567890'
var str2 = 'abc345'
var str3 = '%#34567fhg7'
var str4 = '1234567890'

const exchange = (str, cap) => {
  // split the string and define array
  const arr = str.split('')
  // condtional to see if string.length is greater than cap
  if (str.length > cap) {
    // we have a string longer than cap, loop over the array, exclude 
    // empty spaces and check if value is a number using isNaN, if it is, 
    // we splice its value using the key with the mask character x
    arr.map((char, k) => char !== ' ' ? Number.isNaN(Number(char)) ? null : arr.splice(k, 1, 'x') : null)
    // return the value as a string by joining the array values together
    return arr.join('')
  } else {
    // return the string as its length is not more than cap
    return str
  }
}

console.log(`${exchange(str, 10)}, length = ${str.length}`)
console.log(`${exchange(str2, 10)}, length = ${str2.length}`)
console.log(`${exchange(str3, 10)}, length = ${str3.length}`)
console.log(`${exchange(str4, 10)}, length = ${str4.length}`)

  • Related