split用于将字符串分割成字符串数组
let str = "hello world, this is my first test!";
console.log(str.split(" ")); // ["hello", "world,", "this", "is", "my", "first", "test!"]
// 如果不写分割符号,默认将每个字母都分割开
console.log(str.split("")); // ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", ",", " ", "t", "h", "i", "s", " ", "i", "s", " ", "m", "y", " ", "f", "i", "r", "s", "t", " ", "t", "e", "s", "t", "!"]
let str1 = "|a|b|c|"
console.log(str1.split("|")); // ["", "a", "b", "c", ""]
// 如果要返回一部分字符
console.log(str.split("", 4));
// split()还可以用于正则表达式(也是返回数组)
// 将字符串以" "一个空格分隔开
console.log(str.split(/\s/g)); // ["hello", "world,", "this", "is", "my", "first", "test!"]
// 将字符串以空格分割开(每个单词之间可能有多个空格)
console.log(str.split(/\s+/g));
网友评论