迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

如何在 JavaScript 中通过正则表达式拆分字符串

作者:迹忆客 最近更新:2022/11/18 浏览次数:

要通过正则表达式拆分字符串,请将正则表达式作为参数传递给 split() 方法,例如 str.split(/[,.\s]/)split() 方法接受一个字符串或正则表达式,并根据提供的分隔符将字符串拆分为一个子字符串数组。

const str = 'one,two.three four';

const result = str.split(/[,.\s]/);

// 👇️ ['one', 'two', 'three', 'four']
console.log(result);

我们传递给 String.split() 方法的唯一参数是分隔符。

该方法在正则表达式的每个匹配项上将字符串拆分为子字符串数组。

正斜杠 // 标记正则表达式的开始和结束。

示例中的正则表达式使用字符类 [] 来匹配方括号之间的任何字符 - 逗号、点和空格。

如果我们需要正则表达式备忘单,请查看 MDN 提供的备忘单。 这是迄今为止最好的。

当我们需要使用多个分隔符拆分字符串时,最常使用字符类。

这是另一个在每个数字上拆分字符串的示例。

const str = 'one1two2three';

const result = str.split(/\d/);
console.log(result); // 👉️ ['one', 'two', 'three']

\d 特殊字符匹配任何数字 0-9。 这与使用范围 [0-9] 相同。

请注意 ,在将 split() 方法与正则表达式一起使用时,您不必传递 g(全局)标志。 这是因为该方法不会在第一次出现时停止。

但是,我们可以使用其他标志。 例如,我们可以使用 i 标志进行不区分大小写的匹配。

const str = 'oneAtwoBthree';

const result = str.split(/[ab]/i);
console.log(result); // 👉️ ['one', 'two', 'three']

字符类 [] 匹配 ab。 我们设置了 i 标志,所以我们匹配字符串中出现的 ab 字符的大写和小写。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便