Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Regex to replace last 4 digit

I have a number variable at JavaScript and i want it replaced in last 4 character. Example:

I have a number 123456789 and i want it to be replaced like this 12345****

Is there any regex to do that in JavaScript?

like image 849
Ridho Fauzan Avatar asked May 09 '16 05:05

Ridho Fauzan


2 Answers

Use replace() with regex /\d{4}$/

var res = '123456789'.replace(/\d{4}$/, '****');
document.write(res);

Regex explanation

Regular expression visualization


Or using substring() or substr()

var str = '123456789',
  res = str.substr(0, str.length - 4) + '****';
document.write(res);
like image 147
Pranav C Balan Avatar answered Sep 27 '22 20:09

Pranav C Balan


You could use substring as well:

var s = '123456789';
var ns = s.substring(0, s.length - 4) + '****';
document.write(ns);
like image 43
AKS Avatar answered Sep 27 '22 21:09

AKS