How to Mask All But Last Four Characters in a String

How to i mask all string characters except for the last 4 characters in Java using parameters?

You can do it with the help of StringBuilder in java as follows,

String value = "S1234567B";
String formattedString = new StringBuilder(value)
.replace(0, value.length() - 4, new String(new char[value.length() - 4]).replace("\0", "x")).toString();
System.out.println(formattedString);

How to mask all but last four characters in a string

positive lookahead

A positive lookahead makes it pretty easy. If any character is followed by at least 4 characters, it gets replaced :

"654321".gsub(/.(?=.{4})/,'#')
# "##4321"

Here's a description of the regex :

r = /
. # Just one character
(?= # which must be followed by
.{4} # 4 characters
) #
/x # free-spacing mode, allows comments inside regex

Note that the regex only matches one character at a time, even though it needs to check up to 5 characters for each match :

"654321".scan(r)
# => ["6", "5"]

/(.)..../ wouldn't work, because it would consume 5 characters for each iteration :

"654321".scan(/(.)..../)
# => [["6"]]
"abcdefghij".scan(/(.)..../)
# => [["a"], ["f"]]

If you want to parametrize the length of the unmasked string, you can use variable interpolation :

all_but = 4
/.(?=.{#{all_but}})/
# => /.(?=.{4})/

Code

Packing it into a method, it becomes :

def mask(string, all_but = 4, char = '#')
string.gsub(/.(?=.{#{all_but}})/, char)
end

p mask('testabcdef')
# '######cdef'
p mask('1234')
# '1234'
p mask('123')
# '123'
p mask('x')
# 'x'

You could also adapt it for sentences :

def mask(string, all_but = 4, char = '#')
string.gsub(/\w(?=\w{#{all_but}})/, char)
end

p mask('It even works for multiple words')
# "It even #orks for ####iple #ords"

Some notes about your code

string.to_s

Naming things is very important in programming, especially in dynamic languages.

string.to_s

If string is indeed a string, there shouldn't be any reason to call to_s.

If string isn't a string, you should indeed call to_s before gsub but should also rename string to a better description :

object.to_s
array.to_s
whatever.to_s

join

puts array.join(", ").delete(", ").inspect

What do you want to do exactly? You could probably just use join :

[1,2,[3,4]].join(", ").delete(", ")
# "1234"
[1,2,[3,4]].join
# "1234"

delete

Note that .delete(", ") deletes every comma and every whitespace, in any order. It doesn't only delete ", " substrings :

",a b,,,   cc".delete(', ')
# "abcc"
["1,2", "3,4"].join(', ').delete(', ')
# "1234"

Masking all characters of a string except for the last n characters

Here's a way to think through it. Call the last number characters to leave n:

  1. How many characters will be replaced by X? The length of the string minus n.
  2. How can we replace characters with other characters? You can't directly modify a string, but you can build a new one.
  3. How to get the last n characters from the original string? There's a couple ways to do this, but the simplest is probably Substring, which allows us to grab part of a string by specifying the starting point and optionally the ending point.

So it would look something like this (where n is the number of characters to leave from the original, and str is the original string - string can't be the name of your variable because it's a reserved keyword):

// 2. Start with a blank string
var new_string = "";

// 1. Replace first Length - n characters with X
for (var i = 0; i < str.Length - n; i++)
new_string += "X";

// 3. Add in the last n characters from original string.
new_string += str.Substring(str.Length - n);

How to mask all characters except last 3 characters on a string display only

To use in a FormControl you need know when is focus and when not then you can use some like

 [ngModel]="condition?(yourFormControl.value|yourpipe):
yourFormControl.value"
(ngModelChange)="! condition && yourFormControl.setValue($event)"

Imagine you has a variable "caracteres" and a FormGroup

  caracteres:number=3;
form=new FormGroup({
name:new FormControl()
mobilenumber:new FormControl(),

})

You can to have some like

<form [formGroup]="form">
<input matInput
(focus)="caracteres=0"
(blur)="caracteres=3"
[ngModel]="caracteres?(form.get('mobilenumber').value|hideChars):
form.get('mobilenumber').value"
(ngModelChange)="!caracteres && form.get('mobilenumber').setValue($event)"
[ngModelOptions]="{standalone:true}"
class="form-control">

<!--see that the rest of your input are in the way-->
<input formControlName="name"/>
</form>

C++ masking all characters of a string except for the last n characters with algorithm

Here's a solution using the algorithm library and iterators. I'm using std::prev to get an iterator 4 characters before end(), then std::fill to replace the digits in the range [begin, end - 4) with '*'.

#include <algorithm>
#include <string>
#include <iterator>
#include <iostream>

int main()
{
std::string barcode = "300001629197835714";
std::fill(barcode.begin(), std::prev(std::end(barcode), 4), '*');
std::cout << barcode;
}

Note that

std::prev(std::end(barcode), 4)

will cause undefined behavior if barcode is less than 4 characters.

How Can I dynamically mask all digits except the last 4 always?

You can easily achieve the result using split, reverse and map

function mask(s) {
let count = 0;
return s
.split("")
.reverse()
.map((n, i) => (!n.match(/\d/) ? n : count < 4 ? (count++, n) : "x"))
.reverse()
.join("");
}

function mask(s) {
let count = 0;
return s
.split("")
.reverse()
.map((n, i) => {
if (!n.match(/\d/)) return n;
else {
return count < 4 ? (count++, n) : "x";
}
})
.reverse()
.join("");
}

console.log(mask("1234 5678 9123 4414"));
console.log(mask("12345678 8234245"));
console.log(mask("12 345678911"));
console.log(mask("12 345678 9 1 1")); // CORNER CASE

How to mask a String to show only the last 3 characters?

This does exactly what you want:

let name = "0123456789"
let conditionIndex = name.characters.count - 3
let maskedName = String(name.characters.enumerated().map { (index, element) -> Character in
return index < conditionIndex ? "x" : element
})
print("Masked Name: ", maskedName) // xxxxxxx789

What happens here is that you get an array of the characters of the string using enumerated() method, then map each character to a value based on a condition:

  • If the index of the character is less than condtionIndex we replace the character with an x (the mask).
  • Else, we just leave the character as is.


Related Topics



Leave a reply



Submit