正则常用方法
match
- str.match(searchStr)
'test123test123'.match('123') // 参数为字符串
- str.match(reg)
'test123test123'.match(/123/g) // 参数为regexp对象
匹配到就返回一个数组(如果regexp带有全局标记g则回返回所有结果,否则只会返回第一个匹配结果),没有匹配到就返回null
replace
- str.replace(reg/replaceStr, replacement)
// 全局标识g可以将全局的匹配到的内容替换
'test123test123'.replace(/test/g, 'practice')
// 第二个参数可以是个函数
'test123test123'.replace(/test/g', item => {
return item.toUpperCase()
})
test
- str.test(testStr)
如果字符串 string 中含有与 regexp 匹配的文本,则返回 true,否则返回 false。
search
- str.search(reg/searchStr)
// 标识符i可以不区分大小写,search只匹配第一个结果
// 匹配到就返回相匹配的子串的起始位置,没有匹配到返回-1
'hello World'.search(/world/i)
修饰符
| 修饰符 | 含义 | 示例 |
|---|---|---|
| i | ignore - 不区分大小写 | 'Hello World'.match(/world/i) |
| g | global - 全局匹配 | 'Hello world, Hello world'.match(/world/g) |
| m | multi line - 多行匹配 | 'runoobgoogle\ntaobao\nrunoobweibo'.match(/^runoob/gm); // 多行匹配 |
| s | 特殊字符圆点 . 中包含换行符 \n | 'google\nrunoob\ntaobao'.match(/runoob./s); // 使用 s,匹配\n |