我想将字母替换成数字,因为它们是在<input type="text">
框中输入的。
目前我使用此代码:
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);
}
//我需要在find_str中查找,但我不知道如何......
$("#find").on('keypress',function(){
find_str = $("#find").val();
alert (Auto(find_str));
});
请告诉我如何在find_str中查找字母以及如何编写此代码?
P.S。:alert()仅用于测试。
答案 0 :(得分:1)
replace
不做数组。有几种替代方案,例如多次替换,但音译似乎很好:
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;
另请注意,您可能会遇到一些焦点问题,这对用户来说真的很烦人,所以如果可能的话,请避免这样的事情。
答案 1 :(得分:0)
replace
将正则表达式(或将转换为正则表达式的字符串)作为第一个参数,使用字符串替换匹配项或函数来计算替换项。
因此,你可以使用它:
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 ));
});
如果你真的需要使用数组,当然你也可以这样做。
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");