0

I would like to replace letters into numbers as they're typed inside an <input type="text"> box.

Currently I use this code:

function Auto(str) 
{
  var search = new Array(
    "q","w","e","r","t","y","u","i","o","p"
  );
  var replace = new Array(
    "1","2","3","4","5","6","7","8","9","0"
  );
  return str.replace(search, replace);
}

// me need make find in find_str but i dont know how...

$("#find").on('keypress',function(){
  find_str = $("#find").val();
  alert (Auto(find_str));
});

Tell me please how make find letter in find_str and how to write this code?

P.S.: alert() only for test.

4

2 回答 2

1

replace doesn't do arrays. There are a couple of alternatives, like multiple replacements, but transliteration seems good:

var map = {q: '1', w: '2', e: '3', r: '4', t: '5', y: '6', u: '7', i: '8', o: '9', p: '0'};
var r = '';

for(var i = 0; i < str.length; i++) {
    r += map[str.charAt(i)] || str.charAt(i);
}

return r;

Also note that you're probably going to run into some focus problems, which are really annoying for users, so avoid things like this if at all possible.

于 2013-01-17T03:24:57.767 回答
0

replace takes a regular expression (or a string that will be converted to a regex) as the first argument and a string to replace matches or a function to compute replacements.

Therefore, you'd use this:

var map = {q:'1', w:'2', e:'3', r:'4', t:'5', y:'6', u:'7', i:'8', o:'9', p:'0'};
var keys = "[";
for (var key in map)
    keys += key.replace(/[\]-]/, "\\$&");
keys += "]";
var regex = new RegExp(keys, "g") // /[qwertyuiop]/g

function auto(str) {
    return str.replace(regex, function(match) {
         return map[match]; // the respective number
    });
}
$("#find").on('keyup', function(){
    alert( auto( this.value ));
});

If you really need to use arrays, of course you can do that, too.

var search =  ["q","w","e","r","t","y","u","i","o","p"],
    replace = ["1","2","3","4","5","6","7","8","9","0"];
var map = {};
for (var i=0; i<search.length && i<replace.length; i++)
    map[ search[i] ] = replace[i];
var regex = new RegExp("["+search.join("").replace(/[\]-]/g, "\\$&")+"]", "g");
于 2013-01-17T03:25:41.020 回答