2021-07-15 14:43:09
在 JavaScript 中,字符串分割主要通过 split() 方法实现,该方法根据指定的分隔符将字符串拆分为数组。以下是详细说明:
1. split() 方法语法:string.split(separator, limit)
separator:分隔符,可以是字符串或正则表达式。若为空字符串(""),则按单个字符分割。
limit(可选):限制返回数组的最大元素数量。若省略,返回所有元素。
示例:
const str = "Hello, World!";// 按逗号分割const arr1 = str.split(","); // ["Hello", " World!"]// 按正则表达式(一个或多个空格)分割const arr2 = str.split(/s+/); // ["Hello,", "World!"]// 限制返回1个元素const arr3 = str.split(",", 1); // ["Hello"]分隔符类型:
单字符:如逗号、空格等。
正则表达式:如 /s+/ 匹配连续空格。
undefined:按字符拆分(等价于 split(""))。
limit 参数:
const str = "1,2,3,4,5";const arr1 = str.split(","); // ["1", "2", "3", "4", "5"]const arr2 = str.split(",", 3); // ["1", "2", "3"]matchAll():通过正则表达式返回所有匹配项的迭代器,适用于复杂模式匹配。
const str = "test1test2";const matches = [...str.matchAll(/test/g)]; // 返回匹配结果的迭代器indexOf() + 手动分割:查找分隔符位置后截取子字符串。
const str = "apple,banana";const index = str.indexOf(",");const part1 = str.slice(0, index); // "apple"const part2 = str.slice(index + 1); // "banana"JavaScript 中字符串分割的核心是 split() 方法,支持灵活的分隔符和结果限制。其他方法如 matchAll() 或 indexOf() 适用于特定场景。根据需求选择合适的方法即可。