Javascript 帮助我优化正则表达式

Javascript 帮助我优化正则表达式,javascript,regex,Javascript,Regex,帮助我优化正则表达式 <form id='myForm'> Enter phone number:<input type="text" id='idMyText' name="myText" onKeyUp="alphaToNum(this.value)"> </form> <script> // on each keypress in input box, I want to capture key pressed, // determine

帮助我优化正则表达式

<form id='myForm'>

Enter phone number:<input type="text" id='idMyText' name="myText" onKeyUp="alphaToNum(this.value)">
</form>

<script>
// on each keypress in input box, I want to capture key pressed,
// determine if key pressed belong to group of identified characters
// if, so then convert to specified numeric equivalent and return character 
// to text box.
// This mapping corresponds to numeric characters on blackberry device.
// Normally user has to press alt+letter to get numbers. This will provide
// quicker access to numeric characters on for numeric fields

function alphaToNum(e) {
    x = e;
    x = (x.replace(/W/, "1"));
    x = (x.replace(/w/, "1"));
    x = (x.replace(/E/, "2"));
    x = (x.replace(/e/, "2"));
    x = (x.replace(/R/, "3"));
    x = (x.replace(/S/, "4"));
    x = (x.replace(/D/, "5"));
    x = (x.replace(/F/, "6"));
    x = (x.replace(/Z/, "7"));
    x = (x.replace(/X/, "8"));
    x = (x.replace(/C/, "9"));  
    document.getElementById('idMyText').value = x;  
}

</script> 

输入电话号码:
//在输入框中的每个按键上,我想捕捉按下的按键,
//确定按下的键是否属于已识别的字符组
//如果是,则转换为指定的等效数字并返回字符
//到文本框。
//此映射对应于blackberry设备上的数字字符。
//通常用户必须按alt+letter键才能获得数字。这将提供
//更快地访问数字字段上的数字字符
功能性α酮(e){
x=e;
x=(x.replace(/W/,“1”);
x=(x.replace(/w/,“1”);
x=(x.replace(/E/,“2”);
x=(x.replace(/e/,“2”);
x=(x.replace(/R/,“3”);
x=(x.replace(/S/,“4”);
x=(x.replace(/D/,“5”);
x=(x.replace(/F/,“6”);
x=(x.replace(/Z/,“7”);
x=(x.replace(/x/,“8”);
x=(x.replace(/C/,“9”);
document.getElementById('idMyText')。值=x;
}

您可以使用
/i
修饰符,这样
/W/i
将同时匹配
W
W
(等等)。但总的来说,这看起来更像是一个翻译表的工作——你只是在替换单个字母,所以正则表达式有点过头了。

这对我来说很有效。。。用另一句话回答。。谢谢

<form id='myForm'>
Enter phone number:<input type="text" id='idMyText' name="myText" onKeyUp="alphaToNum(this.value)">
</form>
<script>

var conversionMap = {W:1,E:2,R:3,S:4,D:5,F:6,Z:7,X:8,C:9,
                     w:1,e:2,r:3,s:4,d:5,f:6,z:7,x:8,c:9};

function alphaToNum(){
    var field = document.getElementById('idMyText');
    var value = field.value;
    var chr = value[value.length-1];
    if(conversionMap[chr]) {
        field.value = value.substr(0,value.length-1) + conversionMap[chr];
    }
    // prevent memory leak.
    field = null;
}

</script> 

输入电话号码:
var conversionMap={W:1,E:2,R:3,S:4,D:5,F:6,Z:7,X:8,C:9,
w:1,e:2,r:3,s:4,d:5,f:6,z:7,x:8,c:9};
函数alphaToNum(){
var field=document.getElementById('idMyText');
var值=field.value;
var chr=值[value.length-1];
if(转换映射[chr]){
field.value=value.substr(0,value.length-1)+转换映射[chr];
}
//防止内存泄漏。
字段=空;
}

replicate of:使用“xcv”作为您的最底层不是更自然吗?从左手边的s到Z有点滑稽。更多讨论请参见!