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.
>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('')
}