2015-10-14 128 views
0

我知道我的代碼是錯誤的,我試圖測試某些字符,並且只要它們存在於輸入字段中的每個字符,它就會傳遞true,否則傳遞false 。在JavaScript中爲特殊字符編寫正則表達式

function isChar(value) { 
    //Trying to create a regex that allows only Letters, Numbers, and the following special characters @ . - () # _ 

    if (!value.toString().match(/@.-()#_$/)) {    
     return false; 
    } return true; 
} 
+0

'.match(/ [A-Z0-9 @ \ - ()#_ $] /)' – Anonymous0day

回答

0

在正則表達式中有意義的字符需要用\進行轉義。因此,例如,您將替換$\$等等其他此類字符。所以最後的正則表達式看起來像:

@.\-()#_\$ 

,因爲你需要逃脫既-$

2

假設你實際上是通過一個角色(你不顯示這是怎麼稱呼),這應該工作:

function isChar(value) { 
 
    if (!value.toString().match(/[[email protected]\-()#_\$]/i)) { 
 
    return false; 
 
    } else 
 
    return true; 
 
} 
 

 
console.log(isChar('%')); // false 
 
console.log(isChar('$')); // true 
 
console.log(isChar('a')); // true

相反,如果你傳遞一個字符串,並想知道如果所有的字符串中的字符是在這個「特殊」的名單,你會想這樣的:

function isChar(value) { 
 
    if (! value.match(/^[[email protected]\-()#_\$]*$/i)) { 
 
    return false; 
 
    } else 
 
    return true; 
 
} 
 

 
console.log(isChar("%$_")); // false 
 
console.log(isChar("a$_")); // true

+1

要求是*「試圖建立一個正則表達式只允許使用字母,數字和以下特殊字符「* – JJJ

+0

謝謝。相應更新。我本身就是在迴避這個問題,跳過了評論。 –

0

\ w類將捕獲字母數字。您提供的(但正確轉義)休息:

function isChar(value) { 
    return value.toString().match(/[\[email protected]\-()#_\$]/) ? true : false 
} 
相關問題