Dividing a string object into an ordered list of substrings and returns them in an array in JavaScript: split()

Java Script @ Freshers.in

The split() method divides a String object into an ordered list of substrings and returns them in an array. The division is done by searching for a pattern, wherein specifying a limit sets the number of splits to be done.

Syntax:

string.split([separator[, limit]])

separator (optional): Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned as a single item in an array.

limit (optional): An integer that specifies the number of splits. Items after the split limit will not be included in the array.

Examples and execution:

To see the split() method in action, you can run the following examples in any JavaScript environment like the browser’s console, online playgrounds, or Node.js.

Basic splitting with a character:

let fruits = "apple,banana,orange";
let fruitArray = fruits.split(",");
console.log(fruitArray); // Outputs: ["apple", "banana", "orange"]
Splitting with a limit:
let animals = "cat,dog,elephant,giraffe";
let limitedAnimals = animals.split(",", 2);
console.log(limitedAnimals); // Outputs: ["cat", "dog"]
Splitting by spaces:
let sentence = "JavaScript is fun!";
let words = sentence.split(" ");
console.log(words); // Outputs: ["JavaScript", "is", "fun!"]
Splitting with a regular expression:
let text = "20-10-2023";
let dateParts = text.split(/-/);
console.log(dateParts); // Outputs: ["20", "10", "2023"]
No separator provided:
let word = "hello";
let characters = word.split();
console.log(characters); // Outputs: ["hello"]
Splitting at every character:
let string = "world";
let charArray = string.split("");
console.log(charArray); // Outputs: ["w", "o", "r", "l", "d"]
Splitting with multiple characters:
let details = "name:John|age:25";
let entries = details.split("|");
for(let i = 0; i < entries.length; i++) {
    let [key, value] = entries[i].split(":");
    console.log(`${key} = ${value}`);
}
// Outputs:
// name = John
// age = 25
Author: user