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"]
let animals = "cat,dog,elephant,giraffe";
let limitedAnimals = animals.split(",", 2);
console.log(limitedAnimals); // Outputs: ["cat", "dog"]
let sentence = "JavaScript is fun!";
let words = sentence.split(" ");
console.log(words); // Outputs: ["JavaScript", "is", "fun!"]
let text = "20-10-2023";
let dateParts = text.split(/-/);
console.log(dateParts); // Outputs: ["20", "10", "2023"]
let word = "hello";
let characters = word.split();
console.log(characters); // Outputs: ["hello"]
let string = "world";
let charArray = string.split("");
console.log(charArray); // Outputs: ["w", "o", "r", "l", "d"]
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
Get more articles on Java Script
Read more on Shell and Linux related articles
Refer more on python here : Python