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
- Split an array into chunks in JavaScript
- Get the YouTube video ID from a URL using 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 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..!! 🙂