Reputation: 810
Is possible in js transform a String in this format
123456789
In something like this
*****6789
I want to use just one statment, something like this but keeping the last four characters.
var a = "12312312312123".replace(/[0-9]/g, "*")
console.log(a)
Upvotes: 3
Views: 1557
Reputation: 20526
A slightly different approach... by creating two capture groups and replacing the first with *
repeated.
const a = '123456789'.replace(/(^\d+)(\d{4}$)/, (m,g1,g2) => '*'.repeat(g1.length) + g2);
console.log(a);
Upvotes: 1
Reputation: 33726
You can use either the function slice
or function substr
and the function padStart
to fill *
from left-to-right.
let str = "1234567893232323232";
console.log(str.slice(5, str.length).padStart(str.length, '*'));
Upvotes: -1
Reputation: 117
Use padStart
const str = '123456789';
console.log(str.slice(-4).padStart(str.length, '*'));
Or
const str = '123456789';
console.log(str.substr(-4).padStart(str.length, '*'));
Upvotes: 1
Reputation: 4488
you could make use of .(?=.{4})
with g
flag:
var a = "12312312312123".replace(/.(?=.{4})/g, '*')
console.log(a)
Upvotes: 7
Reputation: 780818
Split the input into substrings, perform the replacement on the first part, and then append the second part.
var input = "123-456-7890";
var prefix = input.substr(0, input.length - 4);
var suffix = input.substr(-4);
var masked = prefix.replace(/\d/g, '*');
var a = masked + suffix;
console.log(a)
Upvotes: 1