在 JavaScript 中拆分字符串和去除周围的空格
要拆分字符串并去除周围的空格:
-
在字符串上调用
split()
方法。 -
调用
map()
方法迭代数组。 -
在每次迭代中,对字符串调用
trim()
方法以删除周围的空格。
const str = 'one - two - three';
const result = str.split('-').map(element => element.trim());
console.log(result); // 👉️ ['one', 'two', 'three']
第一步是使用 String.split
方法将字符串拆分为数组。
我们传递给 split()
方法的唯一参数是我们要拆分字符串的分隔符。
const str = 'one - two - three';
// 👇️ ['one', 'two', 'three']
console.log(str.split('-'));
我们传递给 Array.map
方法的函数会针对数组中的每个元素(子字符串)进行调用。
在每次迭代中,我们使用 String.trim
方法从字符串中删除前导和尾随空格。
// 👇️ "abc"
console.log(' abc '.trim());
map()
方法返回一个新数组,其中包含我们从回调函数返回的值。
我们可能需要处理一种边缘情况 - 可能有 2 个相同的分隔符彼此相邻。
在多个分隔符彼此相邻的情况下,我们会得到一堆空字符串。
// 👇️ ['one', '', ' two ', '', ' three']
console.log('one -- two -- three'.split('-'));
我们在每个连字符上拆分,但是有两个连字符彼此相邻,所以我们得到第二个连字符的空字符串。
为了处理这种情况,我们可以使用 Array.filter
方法从数组中过滤掉任何空字符串。
const str = ' one -- two -- three ';
const result = str
.split('-')
.map(element => element.trim())
.filter(element => element !== '');
console.log(result); // 👉️ ['one', 'two', 'three']
我们传递给 filter()
方法的函数会为数组的每个元素调用。
在每次迭代中,我们检查元素是否不等于空字符串。
filter()
方法返回一个新数组,其中只包含满足条件的值。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。