Reputation: 527
Lets say I have a string
var unmasked = 'AwesomeFatGorilla'
What I want to do is mask 50%+ of the string from the end.
var masked = unmasked.replace( //REGEX//, '•')
After replacing, the masked string should look like the following:
AwesomeF•••••••••
Since there were 17 letters in my unmasked string, the last 9 letters were masked. Are there any Regex that works with this?
Upvotes: 4
Views: 296
Reputation: 3405
Using Regex .(?!.{n})
:
var unmasked = 'AwesomeFatGorilla'
var num = Math.ceil(unmasked.length / 2)
console.log(unmasked.replace(new RegExp(".(?!.{" + num + "})", "g"), "•"))
Upvotes: 1
Reputation: 102198
Here is a simple alternative, without Regex:
var unmasked = 'AwesomeFatGorilla'
var masked = unmasked.slice(0, Math.floor(unmasked.length) / 2) + "•".repeat(Math.ceil(unmasked.length / 2));
console.log(masked)
You have to adjust the math for odd lengths Thanks to Rhyono comment below, I'm using Math.floor()
and Math.ceil()
to get the behaviour you want for odd lengths.
Upvotes: 3