Getting the masked value of a password field?

41,958

Solution 1

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, '*');

Solution 2

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.

Solution 3

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

alert($("#myfield").val().replace(/./g, '*'));
Share:
41,958
Industrial
Author by

Industrial

I just want to lie on the beach and eat hot dogs. That’s all I’ve ever wanted. Really.

Updated on March 22, 2020

Comments

  • Industrial
    Industrial about 4 years

    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
    
  • Nicola Peluchetti
    Nicola Peluchetti almost 13 years
    Maybe i'm stupid but i understood that he was implying that the there is a 'masked' value of the password. Seeing other answers i'm wrong, i'll edit my answer.
  • Lightness Races in Orbit
    Lightness Races in Orbit almost 13 years
    It's not an answer. It's a comment. I'm not saying that what you wrote in it is wrong.
  • James McCormack
    James McCormack almost 13 years
    I doubt this will affect performance to any discernible degree.
  • Industrial
    Industrial almost 13 years
    That's a clean oneliner. Thank you!
  • James McCormack
    James McCormack almost 13 years
    That's not your point maybe, if your goal is to save a few cpu cycles. My point is to do a simple task in one easily read line, without having to create a helper function.
  • Lightness Races in Orbit
    Lightness Races in Orbit almost 13 years
    This approach promotes poor coding practices. You can solve this problem in a single line without a helper function (although a helper function is the right thing to create here) without resorting to spooling up an entire pattern matching engine.
  • Nicola Peluchetti
    Nicola Peluchetti almost 13 years
    @Zootious i didn't copy your answer, i just edited a previous one i did (we mad the post more or less at the same time and we thought the same thing! :))