一、正則表達式判斷是否包含特殊字符
特殊字符除了字母、數字,還包括符號、空格等,在正則表達式中通過轉義字符\來表示,如\?表示匹配問號。
function hasSpecialChar(str){ let reg = /[\`\~\!\@\#\$\%\^\&\*\(\)\_\+\-\=\{\}\[\]\|\:\;\"\'\\,\.\?\/\s]/; return reg.test(str); }
上述代碼使用了字符集 [],表示匹配其中任意一個字符。使用\s匹配空格,\\用來轉義。
二、正則表達式字符串中包含指定字符
在正則表達式中使用 | 來匹配多個條件,可以用來判斷字符串中是否包含指定字符,如下例所示判斷是否包含a或b或c。
function hasLetter(str, letter){ let reg = new RegExp(letter); return reg.test(str); } console.log(hasLetter('abcdefg', 'a|b|c')); // true
上述代碼使用了RegExp構造函數,可以動態生成正則表達式對象。
三、正則表達式不包含指定字符串
在正則表達式中使用^表示匹配不包含指定字符或字符串的情況,如下例所示判斷是否不包含abc字符串。
function notContain(str){ let reg = /^((?!abc).)*$/; return reg.test(str); } console.log(notContain('ABCDEFG')); // true console.log(notContain('ABCDabcEFG')); // false
上述代碼使用了負向前瞻式 (?!…),表示後面不包含括號內的內容。後面的.*表示匹配0個或多個任意字符。
四、正則表達式判斷是否包含漢字
正則表達式匹配漢字,需要用到unicode編碼,如下例所示判斷是否包含漢字。
function hasChinese(str){ let reg = /[\u4e00-\u9fa5]/; return reg.test(str); } console.log(hasChinese('hello 世界')); // true console.log(hasChinese('hello world')); // false
上述代碼使用了unicode編碼表示漢字字符範圍 [\u4e00-\u9fa5]。
五、正則表達式判斷是否包含符號
正則表達式匹配符號,需要使用對應符號的轉義字符。\d 表示匹配數字字符,在[]中表示匹配非數字字符。
function hasSymbol(str){ let reg = /[^\d\w]/; return reg.test(str); } console.log(hasSymbol('hello*world')); // true console.log(hasSymbol('helloworld')); // false
上述代碼使用了[]中加^表示非,匹配任意非數字、非字母的字符,即符號。
原創文章,作者:MQSD,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/133810.html