Liam
Liam

Reputation: 9855

Convert characters to asterisks in Javascript

Im trying to write a function that will convert all charactewrs after the first word into asterisks,

Say I have MYFIRSTWORD MYSECONDWORD, id want it to convert to asterisks on Keyup, but only for the second word, rendering it as so...

MYFIRSTWORD ***

I've been using the following only it converts each and every letter, is this possible?

$(this).val($(this).val().replace(/[^\s]/g, "*"));

Upvotes: 1

Views: 8058

Answers (3)

nnnnnn
nnnnnn

Reputation: 150020

I'm not sure about doing it with a single regex, but you can do this:

$("input").keyup(function() {
    var i = this.value.indexOf(" ");
    if (i > -1) {
        this.value = this.value.substr(0, i) 
                   + this.value.substr(i).replace(/[\S]/g, "*");
    }
});

Demo: http://jsfiddle.net/fc7ru/

Upvotes: 3

Ranganadh Paramkusam
Ranganadh Paramkusam

Reputation: 4358

<input type="text" onkeyup='$(this).val($(this).val().replace(/[^\s]/g, "*"));' />

Check in JsFiddle

Upvotes: 1

Kamran Ali
Kamran Ali

Reputation: 5954

you should try this code

var array =  $(this).val().split(" ");
var newValue = "";
for(var i=0; i<array.length; i++) {
  if ( i==0){
    newValue = array[i];
    continue;
  } else{
    newValue+= array[i].replace(/[^\s]/g, "*");
  }
}

$(this).val(newValue);

Upvotes: -1

Related Questions