Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mask name in JS

There’re a lot of examples of masking names with RegExp but I couldn’t find my case.

I want to mask companies names according to the following examples:

ST --> S*
STE --> S*E
STEP --> S**P
Apple --> A***e
Mozilla --> Mo****la
Mozilla Firefox --> Moz**** ****fox
LTD Best Company --> LTD **** ****any
Telecommunications --> Tel************ons
No Matter How Long --> No ****** *** *ong
GRAS Company Name --> GRA* ******* *ame 

Any ideas? Please, help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a loop

function mask(string) {
  const show = string.length > 7 ? 3 : string.length > 5 ? 2 : 1

  const result = []

  for (let i = 0; i < string.length; i += 1) {
    const char = string[i]
    if (i < show || i > string.length - show - 1 || char === ' ') {
      result.push(char)
    } else {
      result.push('*')
    }
  }

  return result.join('')
}
const strings = [
  'ST', // --> S*
  'STE', // --> S*E
  'STEP', // --> S**P
  'Apple', // --> A***e
  'Mozilla', // --> Mo****la
  'Mozilla Firefox', // --> Moz**** ****fox
  'LTD Best Company', // --> LTD **** ****any
  'Telecommunications', // --> Tel************ons
  'No Matter How Long', // --> No ****** *** *ong
  'GRAS Company Name', // --> GRA* ******* *ame 
]

for (const string of strings) {
  console.log(string, '-->', mask(string))
}

function mask(string) {
  const show = string.length > 7 ? 3 : string.length > 5 ? 2 : 1

  const result = []

  for (let i = 0; i < string.length; i += 1) {
    const char = string[i]
    if (i < show || i > string.length - show - 1 || char === ' ') {
      result.push(char)
    } else {
      result.push('*')
    }
  }

  return result.join('')
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading