Javascript Regex: Mask last 50% of the line

Let's say I have a line

var unmasked = 'AwesomeFatGorilla'

What I want to do is mask 50% + lines from the end.

var masked = unmasked.replace( //REGEX//, '•')

After replacement, the masked string should look like this:

AwesomeF•••••••••

Since there were 17 letters in my unmasked string, the last 9 letters were masked. Is there any Regex that works with this?

+4
source share
2 answers

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)
Run codeHide result

You must configure the math for odd lengths Comment Rhyono below, I use Math.floor()and Math.ceil()for the behavior that you want for the odd length.

+3
source

Using Regex .(?!.{n}):

var unmasked = 'AwesomeFatGorilla'
var num = Math.ceil(unmasked.length / 2)
console.log(unmasked.replace(new RegExp(".(?!.{" + num + "})", "g"), "•"))
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1693851/


All Articles