Nagarjuna Reddy
Nagarjuna Reddy

Reputation: 4195

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)

Upvotes: 1

Views: 1871

Answers (4)

PostCrafter
PostCrafter

Reputation: 655

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);

Upvotes: 0

Devendiran Kumar
Devendiran Kumar

Reputation: 223

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); 

Upvotes: 0

Mårten Wikström
Mårten Wikström

Reputation: 11344

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.

Upvotes: 3

Shankar Gangadhar
Shankar Gangadhar

Reputation: 197

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

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

Upvotes: 0

Related Questions