1.匹配11位手機號,開頭字母位1 ^1\d{10}$ 2.匹配姓名,中文3-6位 [\u4e00-\u9fa5]{3,6} 3.匹配密碼,必須是6-16位的字元,只能包含數字、字母、下劃線: $\w{6-16}^ 4.匹配郵箱 ^\w+@\w+(\.\w+){1,2} 5.匹配座機號 ^\d{1, ...
1.匹配11位手機號,開頭字母位1
^1\d{10}$
2.匹配姓名,中文3-6位
[\u4e00-\u9fa5]{3,6}
3.匹配密碼,必須是6-16位的字元,只能包含數字、字母、下劃線:
$\w{6-16}^
4.匹配郵箱
^\w+@\w+(\.\w+){1,2}
5.匹配座機號
^\d{1,3}-\d{4,8}$
6.匹配一個正數
^\d+(\.\d+)?$
7.匹配一個小數
^-?\d+\.\d+
8.匹配一個整數
^-?\d+$
9.寫一個正則表達式,去匹配一個字元串,得到匹配的次數,和匹配的結果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var reg = /\d{3}/g; var s = "1234a;sdfja;sd234lkfjasldkfj"; var n = 0; while(result = reg.exec(s)){ n++; console.log(result[0]); } console.log(`匹配${n}次`); </script> </body> </html>index.html
10.得到一個字元串中中文字元的數量:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var reg = /[\u4e00-\u9fa5]/g; var s = "1234a;s水電費234lkfjasldkfj"; var n = 0; while(reg.test(s)){ n++; } console.log(n); </script> </body> </html>index.html
11.過濾敏感詞,將一個字元串中出現的敏感詞替換為3個星號:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var senWords = ["小明", "小紅", "小王"]; //將字元串中敏感辭彙替換為指定的字元串 function filterSensitiveWords(s, repStr){ var reg = new RegExp(`(${senWords.join("|")})+`,"g"); return s.replace(reg, repStr); } console.log(filterSensitiveWords("小明小紅小王三個人去上學,課堂上小明調皮搗蛋,小紅認真聽課,小王在發呆", "***")); </script> </body> </html>index.html
12.將一串數字從後向前每三個數字用逗號隔開:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var s = "123123123"; //不是字元邊界,後面是三個數字出現1到多次直到結束,全局匹配 var reg = /\B(?=(\d{3})+$)/g; console.log(s.replace(reg, ",")); </script> </body> </html>index.html
結果展示:
13.判斷密碼強度,要求密碼中必須出現小寫字母、大寫字母、數字、特殊字元(!@#_,.):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> //判斷密碼強度,要求密碼中必須出現小寫字母、大寫字母、數字、特殊字元(!@#_,.) var s = "123asdf&AAA("; var reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[(!#_,.)]).{6,12}$/; console.log(reg.test(s)); </script> </body> </html>index.html