一、RegExp 对象常用方法
方法 | 描述 |
---|---|
test | 检索字符串中指定的值。返回 true 或 false。 |
二、支持正则表达式的 String 对象的常用方法
方法 | 描述 |
---|---|
search | 检索与正则表达式相匹配的值。 |
match | 找到一个或多个正则表达式的匹配。 |
replace | 替换与正则表达式匹配的子串。 |
三、正则表达式
1. 匹配任意字符
使用通配符.
作为任何字符的占位符
const testRegex = /.ui/gi,
testString = "Cuiht CUIHT cuiht";
console.log(testString.match(testRegex));// ["Cui", "CUI", "cui"]
2. 匹配字母
使用字符集内的范围[a-z]
const testRegex = /[a-z]ui/gi,
testRegex_ab = /[ab]ui/gi,
testString = "Cuiht CUIHT cuiht";
console.log(testString.match(testRegex));// ["Cui", "CUI", "cui"]
console.log(testString.match(testRegex_ab));// null
3. 匹配数字
使用字符集内的范围[0-9]
,匹配所有数字[0-9]
简写\d
,匹配所有非数字\D
const testRegex = /[0-3]cht/g,
testRegex_Number = /\d/g,
testRegex_notNumber = /\D/g,
testString = "1cht 2cht 3cht 4cht 5cht";
console.log(testString.match(testRegex)); // ["1cht", "2cht", "3cht"]
console.log(testString.match(testRegex_Number)); // ["1", "2", "3", "4", "5"]
console.log(testString.match(testRegex_notNumber)); // ["c", "h", "t", " ", "c", "h", "t", " ", "c", "h", "t", " ", "c", "h", "t", " ", "c", "h", "t"]
4. 匹配所有字母及数字
匹配所有字母及数字使用\word
简写\w
,匹配所有非字母及数字\W
const testRegex = /\wcht/g,
testRegex_Word = /\w/g,
testRegex_notWord = /\W/g,
testString = "1cht 2cht 3cht";
console.log(testString.match(testRegex)); // ["1cht", "2cht", "3cht"]
console.log(testString.match(testRegex_Word)); // ["1", "c", "h", "t", "2", "c", "h", "t", "3", "c", "h", "t"]
console.log(testString.match(testRegex_notWord)); // [" ", " "]
5. 匹配中文
const testRegex = /[\u4e00-\u9fa5]/g,
testString = "测试123 2cht 3cht";
console.log(testString.match(testRegex)); // ["测", "试"]
6. 匹配空格
匹配空格和回车符使用\s
,匹配非空格和回车符\S
const testRegex_S = /\s/g,
testRegex_notS = /\S/g,
testString = "1cht 2cht 3cht";
console.log(testString.match(testRegex_S)); // [" ", " "]
console.log(testString.match(testRegex_notS)); // ["1", "c", "h", "t", "2", "c", "h", "t", "3", "c", "h", "t"]
7.匹配多个模式
使用操作符号|
const testRegex = /yes|no|maybe/,
testString = "yes",
testString1 = "yo";
console.log(testRegex.test(testString)); // true
console.log(testRegex.test(testString1)); // false
8.提取变量
const testRegex_i = /Cuiht/i,
testRegex_g_i = /Cuiht/gi;
testString = "Cuiht CUIHT cuiht";
// 提取第一个不区分大小写匹配项
console.log(testString.match(testRegex_i));// ["Cuiht"]
// 提取所有不区分大小写匹配项
console.log(testString.match(testRegex_g_i));// ["Cuiht", "CUIHT", "cuiht"]