b @[TOC]
.test() 测试字符是否存在于字符串中 /coding/
.test() 方法会把编写的正则表达式和字符串(即括号内的内容)匹配,如果成功匹配到字符,则返回 true,反之,返回 false
测试字符串内是否有对应字符
let testStr = "Hello, my name is Kevin.";
let testRegex = /Kevin/;
testRegex.test(testStr);
任何其他形式的 Kevin 都不会被匹配。 例如,正则表达式 /Kevin/ 不会匹配 kevin 或者KEVIN
匹配多个文字字符串
/yes|no/
使用|分隔
匹配时忽略大小写 i
使用 i 标志忽略大小写
/ignorecase/i
这个字符串可以匹配字符串 ignorecase、igNoreCase 和 IgnoreCase。
.match() 提取匹配项
"Hello, World!".match(/Hello/);
let ourStr = "Regular expressions";
let ourRegex = /expressions/;
ourStr.match(ourRegex);
第一个 match 将返回 ["Hello"] 第二个将返回 ["expressions"]
全局匹配(搜索多次) g
可使用 g 标志,多次搜寻或提取模式匹配
在正则表达式上可以有多个标志,比如 /search/gi
let testStr = "Repeat, Repeat, Repeat";
let repeatRegex = /Repeat/g;
testStr.match(repeatRegex);
match 返回值 ["Repeat", "Repeat", "Repeat"]
用通配符匹配任何内容(模糊匹配) 通配符(.)
例如,如果想匹配 hug、huh、hut 和 hum,可以使用正则表达式 /hu./
let humStr = "I'll hum a song";
let hugStr = "Bear hug";
let huRegex = /hu./;
huRegex.