JavaScript 中拆分一个字符串并保留空白
要拆分保留空格的字符串,请调用 split()
方法并向其传递以下正则表达式 - /(\s+)/
。 正则表达式在拆分字符串时使用捕获组来保留空格。
const str = 'apple banana kiwi';
const results = str.split(/(\s+)/);
// 👇️ ['apple', ' ', 'banana', ' ', 'kiwi']
console.log(results);
如果希望避免使用正则表达式,请向下滚动到下一部分。
我们传递给 String.split 方法的唯一参数是一个正则表达式。
正斜杠
//
标记正则表达式的开始和结束。\s
特殊字符匹配空格(空格、制表符、换行符)。加号+
匹配前面的项目(空格)一次或多次,换句话说,它将多个连续的空格折叠为 1。括号()
称为捕获组,允许我们匹配字符并将其包含在结果中。
下面是可视化捕获组如何工作的简单方法。
console.log('abc'.split(/b/)); // 👉️ ['a', 'c']
console.log('abc'.split(/(b)/)); // 👉️ ['a', 'b', 'c']
第二个示例使用捕获组 ()
来匹配 b 字符,但仍将其包含在结果中。
如果希望避免使用正则表达式,可以链式调用
split()
和join()
方法。
此方法仅适用于空格,不适用于制表符或换行符。
const str = 'apple banana kiwi';
const result = str.split(' ').join('# #').split('#');
console.log(result); // 👉️ ['apple', ' ', 'banana', ' ', 'kiwi']
我们首先在每个空格上拆分字符串,以获得包含字符串中单词的数组。
const str = 'apple banana kiwi';
// 👇️ ['apple', 'banana', 'kiwi']
console.log(str.split(' '));
下一步是使用 join()
方法将数组转换为字符串。
const str = 'apple banana kiwi';
// 👇️ "apple# #banana# #kiwi"
console.log(str.split(' ').join('# #'));
我们使用了哈希 #
,但是我们可以使用任何字符,只要中间有一个空格即可。
最后一步是在每个散列上拆分字符串。
const str = 'apple banana kiwi';
const result = str.split(' ').join('# #').split('#');
console.log(result); // 👉️ ['apple', ' ', 'banana', ' ', 'kiwi']
选择哪种方法是个人喜好的问题。 在这种情况下,我会使用正则表达式,因为我发现它更直接、更直观。
相关文章
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
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。