如何在 JavaScript 中通过正则表达式拆分字符串
要通过正则表达式拆分字符串,请将正则表达式作为参数传递给 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']
字符类 []
匹配 a 或 b。 我们设置了 i
标志,所以我们匹配字符串中出现的 a 和 b 字符的大写和小写。
相关文章
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 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。