Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript replace first 5 characters with *

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
like image 881
Debopam Avatar asked Mar 09 '26 20:03

Debopam


2 Answers

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'))))
like image 138
anubhava Avatar answered Mar 11 '26 08:03

anubhava


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))); 
like image 37
Orangel Marquez Avatar answered Mar 11 '26 08:03

Orangel Marquez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!