(正则表达式)
声明正则表达式的两种类型:
var reg = new RegExp("hello");
var reg = /hello/;
- test(): 检索字符串中的指定值,若存在,返回值为true .不存在,返回值为 false.
- exec(): 检索字符串中的指定值,若存在,返回该值.否则,返回null .
- match(): 在字符串内检索指定的值,或找到一个或多个正则表达式的匹配.
- search(): 检索与正则表达式相匹配的子字符串.
- replace(): 字符串替换
- split(): 字符串分割
example
var str = "hello world";
var patt = /hello/;
console.log(patt.test(str));
console.log(patt.exec(str));
console.log(str.match(patt));
console.log(str.search(/he/);
console.log(str.replace(/he/,"pp"));
console.log(str.split(/o/));
全局变量和区分大小写
var str = "hello world";
var patt = /hello/g; //全局变量
var patt1 = /hello/i; //不区分大小写
正则规则
规则 | 作用 |
---|---|
/[a-z]/ | 匹配a到z的全部字符 |
/[^a-z]/ | 匹配不是a到z的全部字符 |
/this|are/ | 匹配this元素或are元素 |
/t..s/ | 联合,匹配某些字符串,中间有几个点,就需要匹配几个字符 |
/\w/ | 查找单词字符(字母,数字,下划线) |
/\W/ | 查找非单词字符 |
/\d/ | 查找数字 |
/\s/ | 查找空白字符 |
/\S/ | 查找非空白字符 |
/\b/ | 匹配单词边界, /\bhe/为前匹配, /ust\n/为后匹配 |