1.正则匹配
正则的 test() 方法,测试字符串中是否有符合正则模式的,有返回true,否则返回false
let reg = /前端/
console.log(reg.test('我们都是前端大神')) // true
console.log(reg.test('我们都是端大神')) // false
2.正则提取
正则的exec方法,在一个指定字符串中执行一个搜索匹配
如果匹配成功,exec() 方法返回一个数组,否则返回null
let str = `这是我的手机号:18912345678,有事记得call me~~~`
// 提取手机号
let reg = /1[3-9]\d{9}/
console.log(reg.exec(str)) //[18912345678]
3.元字符-预定义类
\d 匹配0-9的任意一个数字
\D 匹配非0-9数字的任一个字符
\w 匹配任意一个单词字符 a-z A-Z 0-9 下划线_
\W 匹配任意非单词字符
\s 匹配不可见字符(空白)如 空格 换行 \n 制表符 \t
\S 匹配可见字符
. 匹配除换行外的任意字符
对 . 进行转义 \. 表示匹配点本身
4.元字符-字符类
[] 匹配字符集合,[] 自带了 或 的含义
/[abc]/ 匹配a或b或c (匹配的是abc字符中的任意一个)
在 [] 里面写中划线 - 表示范围
/[a-zA-Z0-9]/,匹配 a-z 0-9 A-Z 这些范围内的任意一个
在 [] 里面写 ^ 表示非
/[^abc]/ 正则匹配的是 非 abc,不能是abc中的任一个
console.log(/[^abc]/.test('a3')) // t
console.log(/[^abc]/.test('c4')) // t
console.log(/[^abc]/.test('f8')) // t
console.log(/[^abc]/.test('abc')) // f
console.log(/[^abc]/.test('afbc')) // t
5.元字符-边界符
^ 表示以谁开始
$ 表示以谁结束
^ $ 一起使用 表示精确匹配 使用场景:表单校验
console.log(/^chuan$/.test('chuang')) // f
console.log(/^chuan$/.test('dachuan')) // f
console.log(/^chuan$/.test('chuanchuan')) // f
console.log(/^chuan$/.test('chuan')) // t
6.元字符-量词
* >=0 次 {0,}
+ >=1 次 {1,}
\? 0 或 1 次 {0,1}
{m} 等于 m次
{m,} 大于等于 m次
{m,n} m到n次,包含m和n次
注意点:量词就近修饰,逗号左右两侧不能出现空格
console.log(/chuan{2}/.test('chuanchuan')) // false
console.log(/chuan{2}/.test('chuann')) // true
console.log(/(chuan){2}/.test('chuanchuan')) // true
7.正则优先级
或 | 优先级最低
()优先级最高
// | 优先级最低 左右两边都是个单独的整体
// 匹配的是 f 或 boot
console.log(/f|boot/.test('f')) // t
console.log(/f|boot/.test('foot')) // t
console.log(/f|boot/.test('boot')) // t
console.log(/f|boot/.test('boo')) // f
console.log(/f|boot/.test('foo')) // t
console.log(/f|boot/.test('oot')) // f
// () 优先级最高
// 正则匹配的是 foot 或 boot
console.log(/(f|b)oot/.test('f')) // f
console.log(/(f|b)oot/.test('foo')) // f
console.log(/(f|b)oot/.test('boo')) //f
console.log(/(f|b)oot/.test('oot')) // f
console.log(/(f|b)oot/.test('foot')) // t
console.log(/(f|b)oot/.test('boot')) // t
8.正则修饰符与正则替换
语法:/表达式/修饰符
g---global 全局匹配搜索 找所有的
i---ignore 忽略大小写
字符串有replace方法 替换
语法: 字符串.replace(正则表达式, '替换的文本')
let str = ' abc def abcx yzABCsff '
// 需求:将所有的空格去除掉
console.log(str.replace(/\s/g, ''))
// 把所有 a或A 替换成x
console.log(str.replace(/a/ig, 'x'))
//过滤敏感词
//激情 或 基情字眼替换成 **
let str='这节课很有基情,激情满满'
console.log(str.replace(/激情|基情/g, '**'))
9.拓展:change事件及document.documentElement.scrollTop
change 失去焦点 并且内容改变了才会触发
input.addEventListener('change', function () {
console.log('change了')
})
document.documentElement.scrollTop没有过渡属性