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, m
Solution 1:
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);
Solution 2:
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("*"));
Post a Comment for "Replace All Characters In Specific Group To Asterisks"