1. reg.test(str)
param:待匹配字符串
return:true/false
console.log(/hello/i.test('HelloWorld'))
//true
console.log(/hello/.test('HelloWorld'))
//false
2. reg.exec(str)
param:待匹配字符串
return:array array[0]表示正则匹配到的字符串
var reg = /\d+/g;
var str = 'abcdt23tStri12';
var result = reg.exec(str);
console.log(result);//result[0]
//["23", index: 5, input: "abcdt23tStri12", groups: undefined]
3. reg.exec(str)分组
param:待匹配字符串
return:array
let str = '<a href="http://www/baidu.com">百度</a>';
// 提取 url 和 文本
const reg = /<a href=(.*)>(.*)<\/a>/;
const result = reg.exec(str);
console.log(result)//result[1]、result[2]
//?<url>分组名字
let str2 ='<a href="http://www.baicu.com">百度</a>';
// 提取 url 和 文本
const reg2 = /<a href="(?<url>.*)">(?<text>.*)<\/a>/;
const result2 =reg2.exec(str2)
console.log(result2);
正则常用方法
//URL
let URL = /^http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?$/;