正则表达式
正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。
常用方法
//test()方法 查找是否有匹配的值 //该方法返回true或者false
//注意用法 正则表达式在前 语法:
// pattern.test(str)
var pattern1 = /world/;
var str1 = "hello world ,and the world is beautiful!";
console.log(pattern1.test(str1)); //true
//exec()方法 查询匹配值的信息
//注意用法 正则表达式在前 语法:
// pattern.test(str)
var pattern2 = /world/; //该方法有没有g不影响结果 i有效
var str2 = "hello world ,and the world is beautiful!";
console.log(pattern2.exec(str2)); //返回第一个匹配值的伪数组
//["world", index: 6, input: "hello world ,and the world is beautiful!", groups: undefined]
//match()方法
//与exec()不同在于该方法属于string的正则表达方法,exec属于正则表达式方法
//用法也不同 全局变量g有效 g为全局 i为不区分大小写
var pattern3 = /world/gi;
var str3 = "hello World ,and the world is beautiful!";
console.log(str3.match(pattern3)); //(2) ["World", "world"] 返回匹配值伪数组
//search()方法 返回匹配值的索引值
var pattern4 = /world/i;
var str4 = "hello World ,and the world is beautiful!";
console.log(str4.search(pattern4)); // 6
//replace()方法 替换匹配值 但不改变原来字符串
var pattern5 = /world/i;
var str5 = "hello World ,and the world is beautiful!";
console.log(str5.replace(pattern5, "test")); //hello test ,and the world is beautiful!
console.log(str5); //hello World ,and the world is beautiful!
好用的工具网址推荐
生成正则表达式:
https://c.runoob.com/front-end/854
查看正则表达式语义:
https://regexper.com/