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:
Flowchart:

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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join