The split() method in JavaScript is used to split a string into an array of substrings based on a specified separator.
Syntax: string.split(separator, limit)
- separator: The string or regular expression used to specify where to split the string. If omitted, the entire string will be a single element in the resulting array.
- limit (optional): An integer specifying a limit on the number of splits to be found. The split method still splits the string at each occurrence of the separator, but the resulting array will contain at most "limit" elements. Any trailing empty strings after the limit are not included in the array.
Example:
let str = "Hello,World";
let parts = str.split(",");
console.log(parts); // Output: ["Hello", "World"]
Explanation:
- We have a string str containing "Hello,World".
- We use split(",") to split the string at each comma (",").
- The resulting array parts contains two elements: "Hello" and "World".
If we want to split a string by each character, we can pass an empty string `""` as the separator.
Code Compiler Link: https://app.singhteekam.in/codecompiler/