How to split a string in JavaScript
📅November 16, 2021
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.
Checkout more articles on JavaScript
- array-into-chunks-in-javascript" title="Split an array into chunks in JavaScript">Split an array into chunks in JavaScript
- video-id-from-a-url-using-javascript" title="Get the YouTube video ID from a URL using JavaScript">Get the YouTube video ID from a URL using JavaScript
- math-functions-in-javascript" title="Math functions in JavaScript">Math functions in JavaScript
- Trim string from the dynamic object in JavaScript
- Remove the first element from an array in JavaScript
The `split()` function has an optional parameter called `separator`. The `separator` can be a simple string or it can be Regular Expression">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 = 'Clue Mediator'
var subparts = str.split(" ");
console.log(subparts);
// Output: ["Clue", "Mediator"]
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..!! 🙂