1

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)

1
  • That's because String.prototype.replaceWith doesn't exist. Commented Mar 8, 2016 at 11:16

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

simply, .replace(/.(?=.{4})/g, 'X')
0
 var sno = "TEST123";
  id.slice(-5); 
  id.slice(-1); 

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.