如何使用 JavaScript 通过连字符拆分字符串
使用 split()
方法通过连字符拆分字符串,例如 str.split('-')
。 split
方法将分隔符作为参数,并根据提供的分隔符拆分字符串,返回一个子字符串数组。
const str = 'one-two-three';
const result = str.split('-');
console.log(result); // 👉️️ ['one', 'two', 'three']
const [first, second, third] = result;
console.log(first); // 👉️ "one"
console.log(second); // 👉️ "two"
console.log(third); // 👉️ "three"
我们传递给 String.split
方法的唯一参数是我们想要拆分字符串的分隔符。
该方法返回一个字符串数组,在每次出现提供的分隔符时拆分。
在我们的示例中,字符串包含 2 个连字符,因此数组共有 3 个元素。
为了将数组的值赋给变量,我们使用了解构赋值。
这种语法允许我们在一行中将数组的值解包到多个变量中。
如果不需要,我们甚至可以跳过某个值。
const str = 'one-two-three';
const result = str.split('-');
// 👇️ ['one', 'two', 'three']
console.log(result);
const [, , third] = result;
console.log(third); // 👉️ "three"
我们添加了 2 个逗号来表示我们对前两个数组元素不感兴趣。
另一种方法是访问特定索引处的数组元素。
const str = 'one-two-three';
const result = str.split('-');
console.log(result); // 👉️️ ['one', 'two', 'three']
const first = result[0];
const second = result[1];
const third = result[2];
console.log(first); // 👉️ "one"
console.log(second); // 👉️ "two"
console.log(third); // 👉️ "three"
我们使用括号 []
符号语法来访问数组元素并将它们分配给变量。
索引在 JavaScript 中是从零开始的,这意味着数组中的第一个元素的索引为 0,最后一个元素的索引为
array.length - 1
。
这种方法实现了与使用解构赋值相同的结果,但是有点冗长。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。