How to split a string into an array in JavaScript
📅August 21, 2022
Today we will show you how to split a string in JavaScript. Here we will use the split()
function to explode or split a string in JavaScript.
The split function returns an array that contains all the subparts as ordered array items.
Example 1: Splitting the string based on the single space
var str = 'Code Premix'
var subparts = str.split(" ");
console.log(subparts);
// Output: ["Code", "Premix"]
Example 2: Splitting the string based on the -
var str = '16-11-2021'
var subparts = str.split("-");
console.log(subparts);
// Output: ["16", "11", "2021"]
Example 3: Split a string with multiple separators
var str = 'Hello awesome, world!'
var subparts = str.split(/[\s,]+/);
console.log(subparts);
// Output: ["Hello", "awesome", "world"]
That’s it for today.
Thank you for reading. Happy Coding..!!