2013-02-20 98 views
3

有誰知道我該如何替換數字和符號(不包括破折號和單引號)?用jquery替換數字和符號/ javascript

例如: 如果我有一個字符串「ABDHN'S-J34H @#$」; 如何將數字和符號替換爲空並返回值「ABDHN'S-JH」?

我有下面的代碼來重放所有的字符和符號,以空,只返回我數

$(".test").keyup(function (e) { 
    orgValue = $(".test").val(); 
    if (e.which != 37 && e.which != 39 && e.which != 8 && e.which != 46) { 
     newValue = orgValue.replace(/[^\d.]/g, ""); 
     $(".test").val(newValue); 
    } 
}); 

回答

1

你應該只允許字母,儀表板和單引號,像這樣:

newValue = orgValue.replace(/[^a-zA-Z'-]/g, ""); 

其他任何內容都將被替換爲「」。

+0

你的意思 - 'NEWVALUE = orgValue.replace(/ [^ A-ZA-Z'-。]/g,「」);' – 2013-02-20 03:50:37

+0

@Javier是的,謝謝。 :) – Kaeros 2013-02-20 03:52:35

1

你可以使用這個表達式:

string.replace(/^[a-zA-Z'-]+$/, '') 

這個^字符類[]內將否定匹配。此正則表達式將其他所有的字符轉換比a-zA-Zsingle quotehyphen

1

你可以通過鍵盤上的鍵碼值跳過它們替換符號。

爲鍵碼值鏈接reglar鍵盤: http://www.w3.org/2002/09/tests/keys.html

 $("#your control").bind("keydown keyup", doItPlease); 

function doItPlease(e) 
{ 
// First 2 Ifs are for numbers for num pad and alpha pad numbers 
if (e.which < 106 && e.which > 95) 
{ 
    return false; // replace your values or return false 
} 
else if (e.which < 58 && e.which > 47) 
{ 
    // replace your values or return false 
} else { 
    var mycharacters = [8, 9, 33, 34, 35 // get your coders from above link]; 
    for (var i = 0; i < mycharacters.length; i++) { 
     if (e.which == mycharacters[i]) { 
      // replace your characters or just 
      // return false; will cancel the key down and wont even allow it 
     } 
     e.preventDefault(); 

}