Masking a string JavaScript


The above problem statement is about masking a substring within a string with the help of asterisks in Javascript. So we have to create a function to get the string with some hidden characters.

Understanding the problem statement

In the above problem statement we have to mask a substring within a string with the help of asterisks in Javascript. Masking a given string means we have to replace the certain characters in the given string with some other characters. Normally the asterisks used to hide sensitive information such as passwords, credit card numbers and other confidential data.

Logic for the above problem

The problem statement gives an example code snippet which shows how to implement a function which takes three parameters: the input string, the starting index of the substring to be masked and the ending index of the substring which is to be masked. The function will replace the characters in the substring with the asterisks and return the resulting masked string.

Algorithm

Step 1 − Create the function to get the masking string. This function will take input string str, the starting index and the ending index of substrings.

Step 2 − Check the condition for inputs if the string is invalid, empty, negative or greater than. If the condition is true then return the string as it is.

Step 3 − Calculate the mask length of the string. By getting the difference between ending point and starting point.

Step 4 − Then define the masked string by taking the start point and end point and place asterisks at the places where we have to hide the characters.

Step 5 − Return the masked string at the end of the function

Code for the algorithm

// function to get the masking the given string
function maskingString(str, start, end) {
   if (!str || start < 0 || start >= str.length || end < 0 || end > str.length || start >= end) {
      return str;
   }
   const maskLength = end - start;
   const maskedStr = str.substring(0, start) + "*".repeat(maskLength) + str.substring(end);
   return maskedStr;
}
const inputStr = "9876543210";
const maskedStr = maskingString(inputStr, 2, 8);
console.log(maskedStr);

Complexity

The problem statement mentions the complexity of the algorithm which is used to implement this function is O(n). Here n is the length of the input string. This means that the time the function takes to mask the substring is equally proportional to the length of the input string.

Conclusion

The above algorithm presents a common programming problem of masking a substring in a string and gives an example solution in Javascript with its complexity analysis.

Updated on: 18-May-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements