3

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
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Industrial
  • 41,400
  • 69
  • 194
  • 289
  • The masked value is just a series of the same characters. It's useless. – Evan Mulawski Jul 21 '11 at 14:54
  • Really though, why would you need the "masked value"? You just want the number of characters right? Some browsers show asterisks, some show big dots, etc. – Wesley Murch Jul 21 '11 at 14:55
  • What do you mean the masked value?The masked value is simply the clear text but obfuscated so that other people can't see it.The password of course is sent as is (the value IS what you enter, if you write 'password' in a password field, the value of that field IS password) otherwise how would the server check if your username/password combo is correct? – Nicola Peluchetti Jul 21 '11 at 15:00

3 Answers3

10

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, '*');
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
3

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.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

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

alert($("#myfield").val().replace(/./g, '*'));
James McCormack
  • 9,217
  • 3
  • 47
  • 57
  • I doubt this will affect performance to any discernible degree. – James McCormack Jul 21 '11 at 14:59
  • 1
    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. – James McCormack Jul 21 '11 at 15:06
  • 2
    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. – Lightness Races in Orbit Jul 21 '11 at 15:12