帮我优化正则表达式

时间:2010-10-06 14:34:34

标签: 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 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> 

2 个答案:

答案 0 :(得分:2)

您可以使用/i修饰符,因此/W/i将匹配wW(等)。但总而言之,这看起来更像是翻译表的工作 - 你只是用单个字母代替,所以正则表达式对此有点过分。

答案 1 :(得分:0)

这对我有用......在另一个帖子中回答..谢谢!

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