I need Javascript Regex to replace the first 5 characters. Below are a few examples. The first line is the input and the second is the expected output. Could you please let me know how to achieve this?
I have tried follwoing. But none of them is working if the input is less than 4.
.{5} to ***** and ^\d{5} to *****
Examples
123456789
XXXXX6789
123
XXX
123456
XXXXX6
1
X
12345
XXXXX
You may use a callback function or lambda in .replace():
var arr = ['123456789',
'123',
'123456',
'1',
'12345'];
arr.forEach(el => console.log(el, '::', el.replace(/^\d{1,5}/,
m => m.replace(/\d/g, 'X'))))
Your first regex needs a little tweak, this should work.
let reg = /.{1,5}/
let string = '123456789';
let string2 = '123';
console.log(string.replace(reg, (m) => "X".repeat(m.length)));
console.log(string2.replace(reg, (m) => "X".repeat(m.length)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With