In JavaScript, you can split strings using the split() method. This method divides a string into an array of substrings based on a specified delimiter.
Syntax:
string.split(separator, limit)
separator: The character or regular expression to split the string.
limit: An optional argument to specify the maximum number of splits.
Examples:
1. Splitting by space:
let str = “Hello World”;
let arr = str.split(” “);
console.log(arr); // Output: [“Hello”, “World”]
2. Splitting by a specific character:
let str = “apple,banana,orange”;
let arr = str.split(“,”);
console.log(arr); // Output: [“apple”, “banana”, “orange”]
3. Limit the number of splits:
let str = “one,two,three,four”;
let arr = str.split(“,”, 2);
console.log(arr); // Output: [“one”, “two”]
Use split() to efficiently break down strings in JavaScript based on any delimiter.