JavaScript split() function splits a string into an array according to the specified delimiter. It accepts two parameters: delimiter and limit number of results (optional). Returns an array containing split elements. Usage scenarios include splitting strings by spaces, characters, or regular expressions, and controlling the number of split results.
JavaScript split() function usage
split()
function is used to split characters The string is split into arrays based on the specified delimiter.
Syntax
split(separator, limit)
Parameters
Return value
Returns an array containing split string elements.
Usage
const str = "Lorem ipsum dolor sit amet"; // 使用空格字符分隔 const words = str.split(); console.log(words); // 输出:["Lorem", "ipsum", "dolor", "sit", "amet"] // 使用逗号分隔 const numbers = "1,2,3,4,5"; const numbersArray = numbers.split(","); console.log(numbersArray); // 输出:["1", "2", "3", "4", "5"] // 使用正则表达式分隔 const sentence = "The quick brown fox jumps over the lazy dog"; const words = sentence.split(/\s+/); console.log(words); // 输出:["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"] // 限制拆分结果数量 const hobbies = "Reading, Writing, Coding, Hiking, Photography"; const limitedHobbies = hobbies.split(",", 3); console.log(limitedHobbies); // 输出:["Reading", "Writing", "Coding"]
Note
The above is the detailed content of How to use split() function in js. For more information, please follow other related articles on the PHP Chinese website!