JS 正则表达式常用方法
2024-09-29
21
1. JS 正则表达式
2. 使用字符串方法
3. 使用 RegExp 方法
1. JS 正则表达式
JS 正则表达式语法:
# JS 的正则表达式不需要使用引号包裹,PHP 需要使用引号包裹。修饰符是可选的,可写可不写/正则表达式主体/修饰符
JS 中使用正则表达式的方法比较多,可以按照使用两种类型记忆: 字符串对象方法、正则表达式对象方法
// 字符串对象方法string.search(regexp)// 正则表达式对象方法regexp.test(string)
2. 使用字符串方法
string.search(regexp)
匹配首次出现的下标
const string = 'hello world !'// 返回内容首次出现的位置(下标),没有匹配到时返回 -1const index = string.search(/world/)
string.replace(regexp, new_string)
将首次匹配到的内容进行替换
const string = 'hello world !'// 将首次匹配到的内容进行替换const result = string.replace(/world/, 'vue')
string.match(regexp)
执行正则表达式匹配
const string = 'hello world !'// 下面 result1 和 result2 结果相同// ['world', index: 6, input: 'hello world !', groups: undefined]const result1 = string.match(/world/)const result2 = /world/.exec(string)
string.matchAll(regexp)
执行正则表达式匹配,匹配字符串所有符合条件的内容
const string = 'hello world world !'const result = [...string.matchAll(/world/g)]console.log(result);
3. 使用 RegExp 方法
regexp.test(string)
用于检测一个字符串是否匹配某个模式
const string = 'hello world !'const bool = /world/.test(string)
regexp.exec(string)
执行正则表达式匹配,匹配成功时返回一个数组,匹配失败返回 null
const string = 'hello world !'// ['world', index: 6, input: 'hello world !', groups: undefined]const result = /world/.exec(string)
更新于:19天前赞一波!
相关文章
- 【说站】Python找回文子串的方法
- 【说站】php数组合并的方法
- 【说站】python json保存数据的方法
- 【说站】python系统内置方法如何获取
- 【说站】java反射三种方法
- 【说站】python字符串格式化的方法整理
- 【说站】python代码提速有哪些方法
- 【说站】python ElementTree解析的方法
- 【说站】python shutil有哪些操作文件的方法
- 【说站】java泛型方法的使用注意
- 【说站】java泛型方法的特征
- iOS 图片压缩方法的示例代码
- thinkphp怎么用u方法?ThinkPHP中U方法的使用浅析
- thinkphp怎么用model?ThinkPHP中实例Model方法的区别说明
- thinkPHP简单调用函数与类库的方法
- 常用PC,移动浏览器User-Agent大全
- Python的flask常用函数route()介绍
- HTTP请求方法(HTTP Request Method)
- JS 的 apply 方法
- JS 字符串和数组相互转换
文章评论
评论问答