JavaScript String.prototype.split

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));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章