Mask a Value

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring a JavaScript function called mask that can be used to replace all but the last num characters of a given string with a specified mask character. We will learn how to use this function to create masked strings for sensitive data such as credit card numbers, phone numbers, or email addresses. By the end of this lab, you will have a solid understanding of how to use the mask function in your JavaScript projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") subgraph Lab Skills javascript/variables -.-> lab-28489{{"`Mask a Value`"}} javascript/data_types -.-> lab-28489{{"`Mask a Value`"}} javascript/arith_ops -.-> lab-28489{{"`Mask a Value`"}} javascript/comp_ops -.-> lab-28489{{"`Mask a Value`"}} javascript/template_lit -.-> lab-28489{{"`Mask a Value`"}} end

How to Mask a Value in JavaScript

To mask a value in JavaScript, you can use the mask() function. Follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use String.prototype.slice() to grab the portion of the characters that will remain unmasked.
  3. Use String.prototype.padStart() to fill the beginning of the string with the mask character up to the original length.
  4. If you want to exclude characters from the end of the string, use a negative value for num.
  5. If you don't specify a value for num, the function will default to keeping the last 4 characters unmasked.
  6. If you don't specify a value for mask, the function will default to using the '*' character for the mask.

Here's the code for the mask() function:

const mask = (cc, num = 4, mask = "*") =>
  `${cc}`.slice(-num).padStart(`${cc}`.length, mask);

And here are some examples of how to use the mask() function:

mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
mask(1234567890, -4, "$"); // '$$$$567890'

Summary

Congratulations! You have completed the Mask a Value lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like