Jeremy
Jeremy

Reputation: 1845

Replace all characters in specific group to asterisks

I found this SO post that is close, but I want to expand on this question a bit.

I need to replace each character (within a group of the regex) to an asterisk. For example

Hello, my password is: SecurePassWord => Hello, my password is: **************

I have a regex to grab it into groups, but I can't figure out how to apply this example (from link): str.replace(/./g, '*');

to something like this: str.replace(/(Hello, my password is\: )(\w+)/g, '$1...'); where the ... would be the magic to convert the characters from $2 to asterisks.

Upvotes: 1

Views: 3636

Answers (2)

HollyPony
HollyPony

Reputation: 847

Maybe if you don't especially need regex.

With :

var password = "something";

You can do :

var mystring = "My passsword is " + Array(password.length).join("*");

Or :

var mystring = "My passsword is " + password;
mystring = mystring.replace(password, Array(password.length).join("*"));

Upvotes: 0

Mike Cluck
Mike Cluck

Reputation: 32531

You can use a replacement function with String.prototype.replace which will get the matching text and groups.

var input = 'Hello, my password is: SecurePassWord';
var regex = /(Hello, my password is: )(\w+)/;
var output = input.replace(regex, function(match, $1, $2) {
  // $1: Hello, my password is: 
  // $2: SecurePassWord
  // Replace every character in the password with asterisks
  return $1 + $2.replace(/./g, '*');
});
console.log(output);

Upvotes: 3

Related Questions