Industrial
Industrial

Reputation: 42758

Getting the masked value of a password field?

I've got a normal password field from which I would like to "get" the masked value - yep, that ugly ********** obfuscated value.

HTML:

<input type="password" name="password" value="" id="password"></input>

JS/JQ DOM:

$("#password").val(); // Password in cleartext

Upvotes: 3

Views: 42649

Answers (3)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

If you mean that you want a string that contains as much * as the number of characters you inserted in a password field you could do:

var password = $("#password").val();
password  = password.replace(/./g, '*');

Upvotes: 10

James McCormack
James McCormack

Reputation: 9944

Do a regex replace on $("#myfield").val(); that replaces all characters with * ?

alert($("#myfield").val().replace(/./g, '*'));

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Get a string repeat function on the go, then use this:

repeat('*', $('#myfield').val().length);

or (depending on the implementation you go with):

'*'.repeat($('#myfield').val().length);

My personal suggestion:

function repeat(s, n) {
    return new Array(isNaN(n) ? 1 : ++n).join(s);
}

var password = "lolcakes";
console.log(repeat('*', password.length));
// ^ Output: ********

Live demo.

Upvotes: 3

Related Questions