最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Convert characters to asterisks in Javascript - Stack Overflow

programmeradmin1浏览0评论

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

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, "*"));
Share Improve this question asked Dec 8, 2011 at 12:34 LiamLiam 9,86340 gold badges114 silver badges214 bronze badges 2
  • 4 this.value = this.value.replace( ... ); No need for jQuery here. – Šime Vidas Commented Dec 8, 2011 at 12:37
  • Are you saying that "TEST1 TEST2 TEST3" would bee "TEST1 ***** *****"? – Andrew Jackman Commented Dec 8, 2011 at 12:37
Add a ment  | 

3 Answers 3

Reset to default 3

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/fc7ru/

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

Check in JsFiddle

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);
发布评论

评论列表(0)

  1. 暂无评论