简体   繁体   中英

Angularjs: Show last four characters in a string and replace remaining with 'X'

I'm trying to replace the characters with X , should look something like this XXXXXT123

I tried this:

var sno = 'TEST123';
alert(sno.slice(0,3).replaceWith('X'));

But in the console it is showing an error

Uncaught TypeError: sno.slice(...).replaceWith is not a function(anonymous function)

Do do this (cleverly suggested by @georg ):

sno.replace(/.(?=.{4})/g, "X");

This will do the job:

sno.replace(/^.+(?=....)/, function (str) { return str.replace(/./g, "X"); });

The first regular expression /^.+(?=....)/ matches all but the last four characters.

Those matching characters are fed into the provided function. The return value of that function is what the matching characters should be replaced with.

replace(/./g, "X") replaces all characters with an X .

 var sno = "TEST123";
  id.slice(-5); 
  id.slice(-1); 

alert(Array(chars + 1).join('X') + test.slice(3));

Try something like this, I've split it up to add some explanation

var sno = 'TEST123';
var chars = 4;
var prefix = Array(sno.length - chars + 1).join('X'); // Creates an array and joins it with Xs, has to be + 1 since they get added between the array entries
var suffix = sno.slice(-4); // only use the last 4 chars
alert(prefix + suffix);

It could be achieved by implementing the below logic

var sno = 'TEST1112323';
String.prototype.replaceBetween = function(start, end, text) {
   return this.substr(0, start) + this.substr(start, end).replace(/./g, 'X') + this.substr(end);
};
sno = sno.replaceBetween(0, sno.length - 4, "x");
console.log('replaced text', sno); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM