Open In App

How to replace characters except last with the specified mask character in JavaScript ?

In this article, we have given a number and the task is to replace the characters except for the last character with a specified mask character in JavaScript.

These are the following methods:



Example: Let’s take a number 12345678 and the masking character is * and the number of the last element that we have to skip is 2 In the below image shows that we skip the last two-element, and we mask another character with ‘*’



Approach 1: Using a Naive approach

We can iterate over all the characters except the last one and while iterating we replace each character till the last one.

Here is the implementation:




function maskString(str, maskChar) {
  if (str.length <= 1) {
    return str;
  }
 
  let maskedString = '';
  for (let i = 0; i < str.length - 1; i++) {
    maskedString += maskChar;
  }
  maskedString += str[str.length - 1];
  return maskedString;
}
let originalString = "Hello, Geeks!";
let maskedString = maskString(originalString, "*");
console.log(maskedString);

Output
************!

Approach 2: Using slice() and replace method

We will make one function that can mask the character of the string except for the last element we will give our number as a string.

Example: This example shows the above-explained approach.




// Function for masking the character
function MaskCharacter(str, mask, n = 1) {
 
    // Slice the string and replace with
    // mask then add remaining string
    return ('' + str).slice(0, -n)
        .replace(/./g, mask)
        + ('' + str).slice(-n);
}
 
// Number that we want to mask
let num = 12345678;
 
// Convert number into string
let str = num.toString();
 
// Call function without giving value of n
console.log(MaskCharacter(str, '#'));
 
// Call function with value of n
console.log(MaskCharacter(str, '#', 2));

Output
#######8
######78

Approach 3: Using reduce() method

This task can also be performed with the help of reduce() method. We will make one function that can mask the character of the string except for the last element we will give our number as a string.

Example: This example shows the above-explained approach.




// Function for masking the character
function MaskCharacter(str, mask, n = 1) {
 
    // Slice the string and replace with
    // mask then add remaining string
    return [...str].reduce((acc, x, i) =>
        (i < str.length - n) ? acc + mask : acc + x, '');
}
 
// Number that we want to mask
let num = 12345678;
 
// Convert number into string
let str = num.toString();
 
// Call function without giving value of n
console.log(MaskCharacter(str, '#'));
 
// Call function with value of n
console.log(MaskCharacter(str, '#', 2));

Output
#######8
######78


Article Tags :