-6

is there any method or function that able to convert such scenario? My project need to display userID in this format, the first 3 int/string and last 3 int/string should able to display the number, while middle part should be hashed with *.

Liew Syet Chau
  • 143
  • 3
  • 14
  • 1
    This can be done with the built in substring functions; there are some libraries out there for masking text as well that could help. Can you show us your code attempt? – Explosion Pills Jan 20 '21 at 04:36
  • 1
    Maybe try this? https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – Kay Jan 20 '21 at 04:37
  • Also what will you do if the "userid" is 6 chars? – GetSet Jan 20 '21 at 04:43

3 Answers3

0

Try this simple solution it is just by splitting the text into three sets first middle last and convert the middle

const convertText = (text) => {
  const firstSet = text.slice(0, 3);
  const lastSet = text.slice(text.length - 3, text.length);
  const middleSet = text.slice(3, text.length - 3);
  var starSet = "";
  for (var i = 0; i < middleSet.length; i++) {
    starSet = starSet.concat("*");
  }
  const convertedText = firstSet.concat(starSet, lastSet);
  return convertedText;
};
Ibrahim shamma
  • 399
  • 5
  • 13
0

Since JS strings are immutable, you can only accomplish this by building a new string. One of the easiest ways to do this is by splitting the string into individual characters and inserting them into an array, since arrays are mutable. You can do this using Array.from.

You can then modify individual characters. In your case, since you want to change a range of values so that they are all the same value, you can use Array.fill which will fill a subsection of the array with a value.

Now that you've changed the values, you just have to recombine them into a string, which you can do using Array.join.

let hideMiddle = (str) => Array.from(str).fill("*", 3, -3).join("");
TSA
  • 43
  • 5
0

Its easy, hope the below code helps

const slice = (str) =>{
    let total = ""
    let error = false
    let errorMessage = ""
    if(str != null && str !=""){
        error = false
        let firstThree = str.slice(0, 3)
        let lastThree = str.slice(str.length-3, str.length)
        total = `${firstThree}***${lastThree}`
    }else{
        error = true
        errorMessage = "Please fill the str perimter."
        return errorMessage
    }
    return total
}

// Calling Function
console.log(slice("12345678"))
Evil-Coder
  • 11
  • 1
  • 4