How to use the split() method in JavaScript?

The split() method in JavaScript is used to split a string into an array of substrings, based on a specified separator string.

Syntax:

string.split(separator, limit)
  • separator: Specifies the separator to use for splitting the string.
  • limit (optional): Specifies the number of items to return in the new array.

Examples:

let str = "How,are,you";
let result = str.split(",");
console.log(result);
// Output: [ "How", "are", "you" ]
let str = "How are you";
let result = str.split(" ");
console.log(result);
// Output: [ "How", "are", "you" ]