二十七、正则表达式

二十七、正则表达式

27.1 概述

正则表达式(regular expression) 缩写:RegExp

正则表达式用于匹配字符串中字符组合模式,用于表单验证。

正则字面量: /表达式/;

数据类型:引用数据类型 object

1
2
3
var reg = /abc/;
// 数据类型
console.log(typeof reg); // object

例如:验证用户输入的是否是本地号码:000-1234567

1
2
3
4
5
6
7
8
9
// 获取用户输入
var str = prompt("请输入本地号码");
// 本地号码
var reg = /^\d{3}-\d{7}$/;
if(reg.test(str)){
console.log("没问题");
}else{
console.log("请重新输入");
}

27.2 字符串方法

27.2.1 split()

  • split():将字符串转为数组的方法

  • 参数:要切割的字符串,还可以是正则表达式

  • 返回值:数组

1
2
3
4
5
6
7
8
9
// 字符串
var str = "abxchxdfxrgxs";
// 参数可以直接是字符串
console.log(str.split("x"));

// 参数还可以是正则
var str1 = "abxxxxxchxxxxdfxxxrgxxxs";
console.log(str1.split("x")); //结果会出现多个空数组
console.log(str1.split(/x+/)); //切割的字符串:多个x

UPg1iT.png

27.2.2 match()

  • match() :用于字符串匹配返回数组

  • 参数:字符串、正则

  • 返回值:匹配到的字符串组成的数组 参数可以是正则可用g表示全局匹配

1
2
3
// match()匹配 参数:字符串 返回值:得到abc
var str2 = "ahabcfabcj";
console.log(str2.match("abc"));

UPgcyd.png

1
2
// 参数可以是正则 g 表示全局匹配
console.log(str2.match(/abc/g));

UPgHyj.png

27.2.3 search()

  • search() :用于匹配字符串查找,返回索引值

  • 参数:字符串,正则

  • 返回值:索引值,没有字符串返回-1。 search没有全局匹配,只能返回首次匹配的结果

1
2
3
4
5
6
7
// search() 查找
// 参数:字符串
var str3 = "abcbbbbb";
// 返回首次匹配的结果
console.log(str3.search("b"));
// 参数还可以是正则,search没有全局匹配,只能返回首次匹配的结果
console.log(str3.search(/b/));

UP2npD.png

27.2.4 replace()

  • replace():用于匹配字符串替换

  • 参数:第一个参数:匹配的字符串、正则 第二个参数:新的字符串(只能是字符串)

  • 返回值:替换的字符串

1
2
3
4
5
6
// replace() 替换
var str4 = "www.baidu.com";
// 第一个参数:字符串
console.log(str4.replace("baidu","666"));
// 第一个参数:正则
console.log(str4.replace(/baidu/,"666"));

27.3 正则方法

27.3.1 exec()

  • exec():用于字符串匹配,返回数组

  • 参数:字符串

  • 返回值:包含匹配字符串组成的数组,没有全局匹配,只能将首次匹配的结果输出

1
2
3
4
5
// exec() 匹配
var reg = /abc/;
var str = "abcbbbabcbbb";
// 参数写原字符串
console.log(reg.exec(str));

UP274K.png

27.3.2 test() 是否含有匹配的字符

  • test():用于字符串检测

  • 参数:字符串

  • 返回值:布尔值(检测字符串中是否含有正则表达式匹配的字符)true false

1
2
3
4
5
6
7
8
9
10
11
// test()用于字符串检测
// 检测str2中是否含有abc
var str2 = "ahjabcfj";
var reg = /abc/;
if(reg.test(str2)){
// 如果含有abc,输出“含有”
console.log("含有");
}else{
console.log("没有");
}
console.log(reg.test("abbbc"));

UPRZbn.png

点击查看

本文标题:二十七、正则表达式

文章作者:Mango

发布时间:2020年07月08日 - 22:01:58

最后更新:2020年07月08日 - 22:35:39

原始链接:https://mango185.github.io/post/66220f26.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------