Reputation: 15303
I am trying to replace all characters leaving last four characters. I am trying the following to do that:
var string = params.toString();
string = string.replace(/^.{12}/g,'************');
return string;
at present my string length is 16, But my question is, when my string length changes from 16 to 12 or some other length, I will get the issue because of using the static 12
and *
hash letters.
so, how to get alway replace the *
only on leaving last 4 characters?
Upvotes: 2
Views: 637
Reputation: 43743
The following will work:
var input = "123456789";
var output = input.replace(/.(?=.{4})/g, '*');
console.log(output);
It just does a global replace on all characters which are followed by at least four other characters. Since the last four characters won't have four more that come after them, they won't be replaced. Each matching character is replaced by a single asterisk character.
Upvotes: 3
Reputation: 20885
Create an array of *
and concatenate it with the last 4 characters of your initial string:
const str = "1234567812345678";
const result = [
...new Array(str.length - 3).join('*'),
...str.slice(str.length - 4, str.length)
];
console.log(result);
Upvotes: 0
Reputation: 522752
We can try using the following replacement pattern:
/.*(.{4})/
And then replace your string with the first capture group $1
:
var string = "1234567890";
var pass = Array(string.length-3).join("*") + string.replace(/.*(.{4})/, "$1");
console.log(pass);
But we still need some way to generate the correct number of asterisks for the non final four characters of the string. For this, I use a join trick.
Upvotes: 1