当前位置: 首页 > news >正文

JS 正则表达式常用方法

  • 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)

 

相关文章:

  • SpringBoot引入Layui样式总是出现404
  • 【01】JAVASE-Java基础入门【从零开始学JAVA】
  • 代码随想录算法训练营Day10 | 232.用栈实现队列、225. 用队列实现栈
  • 如何用java复制图片
  • conda修改当前环境中的python版本
  • windows Jenkins运行python+selenium打开浏览器一直无响应,运行中,还没有打开浏览器
  • 【AIGC】基于深度学习的图像生成与增强技术
  • iOS 通过NSURLProtocol拦截WKWebView网络请求
  • Elasticsearch从入门到精通-01认识Elasticsearch
  • 论文阅读:SOLOv2: Dynamic, Faster and Stronger
  • maven的生命周期
  • RV32/64 特权架构 - 特权模式与指令
  • 2-分类问题 SVM 核函数
  • [附源码]计算机毕业设计校园订餐管理系统Springboot程序
  • GitLab CI/CD系列教程(一)
  • html当当书网站 html网上在线书城 html在线小说书籍网页 当当书城网页设计
  • [附源码]JAVA毕业设计课程网站设计(系统+LW)
  • Spring Boot TestEntityManager
  • 【@property的参数copy Objective-C语言】
  • 八股文之设计原则
  • C++图书管理系统(管理员-读者)
  • 高可用方案组件,Keepalived详解
  • MOSFET 和 IGBT 栅极驱动器电路的基本原理学习笔记(一)MOSFET技术
  • Ansible
  • 年产2万吨山楂酒工厂的设计-陈酿工段及车间的设计(lunwen+任务书+cad图纸)
  • Java项目:SSM教师师资管理系统
  • wasm 视频解码渲染实现
  • [YOLOv7/YOLOv5系列改进NO.40]融入适配GPU的轻量级 G-GhostNet
  • 华为机试真题 C++ 实现【连接器问题】【2022.11 Q4新题】
  • 50、IO流
  • Android入门第43天-Activity与Activity间的互相传值
  • 机器学习之过拟合和欠拟合