• Post category:JavaScript
  • Reading time:2 mins read

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 has an optional parameter called separator. The separator can be a simple string or it can be a regular expression.

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..!!

Leave a Reply