w3resource

JavaScript: Replace all but the last number of characters with the specified mask character

JavaScript fundamental (ES6 Syntax): Exercise-85 with Solution

Write a JavaScript program to replace all but the last number of characters with the specified mask character.

  • Use String.prototype.slice() to grab the portion of the characters that will remain unmasked.
  • Use String.padStart() to fill the beginning of the string with the mask character up to the original length.
  • If num is negative, the unmasked characters will be at the start of the string.
  • Omit the second argument, num, to keep a default of 4 characters unmasked.
  • Omit the third argument, mask, to use a default character of '*' for the mask.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const mask = (cc, num = 4, mask = '*') =>
  ('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num);

console.log(mask(1234567890)); 
console.log(mask(1234567890, 3));
console.log(mask(1234567890, -4, '$'));

Sample Output:

******7890
*******890
$$$$567890

Pictorial Presentation:

JavaScript Fundamental: Replace all but the last number of characters with the specified mask character

Flowchart:

flowchart: Replace all but the last number of characters with the specified mask character

Live Demo:

See the Pen javascript-basic-exercise-85-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to create an object with the same keys as the provided object and values generated by running the provided function for each value.
Next: Write a JavaScript program to get the maximum value of an array, after mapping each element to a value using the provided function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

Chunks an array into n smaller arrays

Example:

const tips_chunkIntoN = (arr, n) => {
  const size = Math.ceil(arr.length / n);
  return Array.from({ length: n }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
}
console.log(tips_chunkIntoN([1, 2, 3, 4, 5, 6, 7,8], 4)); 

Output:

[[1,2],[3,4],[5,6],[7,8]]