在 JavaScript 中用多个空格拆分字符串
Split a String by Multiple Spaces in JavaScript
要用多个空格拆分字符串,请调用该split()
方法,并向其传递一个正则表达式,例如str.trim().split(/\s+/)
. 正则表达式将字符串拆分为一个或多个空格并返回一个包含子字符串的数组。
索引.js
const str = ' banana kiwi mango '; const result = str.trim().split(/\s+/); console.log(result); // 👉️ ['banana', 'kiwi', 'mango']
我们在字符串上调用了
String.trim
方法来删除任何前导或尾随空格。
索引.js
console.log(' a '.trim()); // 👉️ "a"
这有助于我们避免
String.split
方法返回的数组包含空元素的情况。
索引.js
const str = ' banana kiwi mango '; // ⛔️ without trim // 👇️ ['', 'banana', 'kiwi', 'mango', ''] console.log(str.split(/\s+/));
我们传递给该
String.split()
方法的唯一参数是一个正则表达式。The forward slashes / /
mark the beginning and end of the regular expression.
The \s
special character matches any whitespace (spaces, tabs or newlines).
The plus
+
matches the preceding item (the space) one or more times. In other words, the plus matches one or more spaces, treating them as a single match.If you ever need help reading a regular expression, check this
regex cheatsheet
from MDN out.
This approach would also work if you need to split the string on multiple
whitespace characters.
index.js
const str = ' banana \n \t kiwi \r\n mango '; const result = str.trim().split(/\s+/); console.log(result); // 👉️ ['banana', 'kiwi', 'mango']
The \s
special characters matches any whitespace including spaces, tabs and
newlines.