1、创建正则对象

let re1 = new RegExp("abc");

let re2 = /abc/;


2、测试匹配

console.log(/abc/.test("abcde"));

// → true
console.log(/abc/.test("abxde"));

// → false


3、字符类
\d Any digit character
\w An alphanumeric character (“word character”)
\s Any whitespace character (space, tab, newline, and similar)
\D A character that is not a digit
\W A nonalphanumeric character

\S A nonwhitespace character

[0-9] [a-z]等, ^表示否定

4、重复

+,    *,     {m,n}

5、group

let cartoonCrying = /boo+(hoo+)+/i;
console.log(cartoonCrying.test("Boohoooohoohooo"));
// → true


6、选择模式

let animalCount = /\b\d+ (pig|cow|chicken)s?\b/;
console.log(animalCount.test("15 pigs"));


7、match

let match = /\d+/.exec("one two 100");
console.log(match);
// → ["100"]
console.log(match.index);
// → 8


8、Dynamically creating RegExp objects

let name = "harry";
let text = "Harry is a suspicious character.";
let regexp = new RegExp("\\b(" + name + ")\\b", "gi");
console.log(text.replace(regexp, "_$1_"));
// → _Harry_ is a suspicious character.


9、search method

console.log(" word".search(/\S/));
// → 2
console.log(" ".search(/\S/));
// → -1


10、The lastIndex property

let pattern = /y/g;
pattern.lastIndex = 3;
let match = pattern.exec("xyzzy");
console.log(match.index);
// → 4
console.log(pattern.lastIndex);
// → 5


11 international

默认只匹配一个代码点,要匹配两个代码点的unicode加上/u选项。




Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐