Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript - How to Mask All Characters Except the Last?
Next article icon

JavaScript - How to Mask All Characters Except the Last?

Last Updated : 07 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the different methods to replace characters except the last with the specified mask character in JavaScript.

1. Using slice() and repeat() Methods

Use slice() to get the last character of the string and repeat() to mask the rest of the characters.

JavaScript
let s = "123456789"; let maskChar = "*"; let masked = maskChar.repeat(s.length - 1) + s.slice(-1);  console.log(masked); 

Output
********9 
  • maskChar.repeat(s.length - 1) creates a string of * characters for all but the last character.
  • s.slice(-1) gets the last character of the string.
  • The result is a concatenation of the masked part and the last character.

2. Using substring() and repeat() Methods

This approach is quite similar to the first, but instead of slice(), we use substring() to get the last character.

JavaScript
let s = "9876543210"; let maskChar = "#"; let masked = maskChar.repeat(s.length - 1) + s.substring(s.length - 1);  console.log(masked); 

Output
#########0 
  • maskChar.repeat(s.length - 1) repeats the mask character for all but the last character.
  • s.substring(s.length - 1) extracts the last character.

3. Using Array.map() and join()

In this we convert the string into an array, masking all but the last character, and then using join() to form the final string.

JavaScript
let s = "abcdefgh"; let maskChar = "$"; let masked = s.split('').map((char, idx) =>  	idx === s.length - 1 ? char : maskChar).join('');  console.log(masked); 

Output
$$$$$$$h 
  • s.split('') converts the string into an array of characters.
  • map() is used to replace each character with the mask unless it's the last character.
  • join('') reassembles the array back into a string.

4. Using replace() with a Regular Expression

This approach uses a regular expression to match all characters except the last one and replace them with the mask character.

JavaScript
let s = "abcdefg"; let maskChar = "&"; let masked = s.replace(/.(?=.{1})/g, maskChar);  console.log(masked);  

Output
&&&&&&g 
  • The regex /(.?=.{1})/g matches all characters except the last one.
  • replace() replaces the matched characters with the mask character (&).

5. Using for Loop with String Concatenation

This is a more manual approach where a loop is used to iterate over the string and build the masked string.

JavaScript
let s = "987654321"; let maskChar = "+"; let masked = "";  for (let i = 0; i < s.length - 1; i++) {     masked += maskChar; } masked += s[s.length - 1];  console.log(masked); 

Output
++++++++1 
  • The loop iterates through the string and adds the mask character for each character except the last one.
  • The last character is appended directly after the loop.

6. Using StringBuilder Approach (Manual String Concatenation)

For larger strings or performance-sensitive situations, manually building a string using string concatenation can be a choice.

JavaScript
let s = "hello123"; let maskChar = "X"; let masked = "";  for (let i = 0; i < s.length - 1; i++) {     masked += maskChar; } masked += s.charAt(s.length - 1);  console.log(masked);  

Output
XXXXXXX3 
  • Concatenate X for all characters except the last one using a loop.
  • charAt(s.length - 1) retrieves the last character.

Next Article
JavaScript - How to Mask All Characters Except the Last?

K

khushindpatel
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-string
  • javascript-functions
  • JavaScript-DSA
  • JavaScript-RegExp
  • JavaScript-Questions

Similar Reads

    JavaScript - How To Get The Last Caracter of a String?
    Here are the various approaches to get the last character of a String using JavaScript.1. Using charAt() Method (Most Common)The charAt() method retrieves the character at a specified index in a string. To get the last character, you pass the index str.length - 1.JavaScriptconst s = "JavaScript"; co
    3 min read
    JavaScript - How to Get the First Three Characters of a String?
    Here are the various methods to get the first three characters of a string in JavcaScript1. Using String.slice() MethodThe slice() method is one of the most commonly used and versatile methods to extract a part of a string. It allows you to specify the start and end positions for slicing the string.
    3 min read
    JavaScript - How to Find the First and Last Character of a String?
    Here are the various methods to find the first and last character of a string in JavaScript.1. Using charAt() MethodThe charAt() method retrieves the character at a specified index.JavaScriptconst s = "JavaScript"; const first = s.charAt(0); const last = s.charAt(s.length - 1); console.log(first); c
    2 min read
    JavaScript - Delete Character from JS String
    In JavaScript, characters can be deleted from the beginning, end, or any specific position in a string. JavaScript provides several methods to perform these operations efficiently.Delete First CharacterTo remove the first character from a string, we can use methods like slice, substring, or regular
    2 min read
    JavaScript - Delete First Character of a String
    To delete the first character of a string in JavaScript, you can use several methods. Here are some of the most common onesUsing slice()The slice() method is frequently used to remove the first character by returning a new string from index 1 to the end.JavaScriptlet s1 = "GeeksforGeeks"; let s2 = s
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences