String split()
In JavaScript, String.split()
method is used to split the string into values by a given delimiter or separator string.
Syntax
str.split(sep)
where
str
is original string.sep
is a string (separator).
split()
method split the string str
using separator string sep
, and returns an array containing the split parts.
Examples
1. In the following program, we take a string in str
, and split this string using delimiter of '-'
.
let str = 'apple-banana-cherry';
let output = str.split('-');
console.log(output);
2. In the following program, we take a string in str
, and split this string by single white space.
let str = 'apple banana cherry';
let output = str.split(' ');
console.log(output);
3. In the following program, we take a string in str
, and split this string using split()
method, but pass no argument to the split()
method for separator parameter.
let str = 'apple banana cherry';
let output = str.split();
console.log(output);