
JavaScript String split()
The split()
method in JavaScript is used to split a string into an array of substrings based on a specified separator. It takes the separator as an argument and returns an array of substrings.
Here’s the syntax of the split()
method:
string.split(separator, limit);
string
: The original string to be split.separator
(optional): The separator used to determine where to split the string. It can be a string or a regular expression. If omitted, the entire string is considered as a single substring in the resulting array.limit
(optional): A numeric value specifying the maximum number of substrings to be returned. If provided, the resulting array will contain at mostlimit
elements. Any remaining text will be included in the last element of the array. If omitted, all occurrences of the separator will be used to split the string.
Here are a few examples of using the split()
method:
Example 1: Splitting a string with a space separator
const str = "Hello, world!";
const words = str.split(" ");
console.log(words); // Output: ["Hello,", "world!"]
Example 2: Splitting a string with a comma separator
const str = "apple,banana,orange";
const fruits = str.split(",");
console.log(fruits); // Output: ["apple", "banana", "orange"]
Example 3: Splitting a string with a regular expression separator
const str = "1-2-3-4-5";
const numbers = str.split(/-/);
console.log(numbers); // Output: ["1", "2", "3", "4", "5"]
Example 4: Limiting the number of substrings returned
const str = "a-b-c-d-e";
const limited = str.split("-", 3);
console.log(limited); // Output: ["a", "b", "c"]
In these examples, the split()
method is used to split the string into substrings based on different separators such as space, comma, or hyphen. The resulting substrings are stored in an array for further processing.
Remember that the original string remains unchanged, and the split()
method returns a new array containing the substrings.