JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to split a string by multiple spaces in JavaScript?

If you want to split a string by multiple spaces, pass a regular expression, i.e., /\s+/ to the split() method. This regular expression will split the string based on one or multiple spaces.

let str = "Chocolate   Pastry    Biscuit  Cake";

let arr = str.split(/\s+/);
console.log(arr); //["Chocolate", "Pastry", "Biscuit", "Cake"]

If a string has leading or trailing spaces, call the trim() method to remove them before calling the split() method. If you don't do this, then the split() method returns an array with empty elements.

let str = "  Chocolate   Pastry    Biscuit  Cake    ";

let arr = str.split(/\s+/);
console.log(arr); //["", "Chocolate", "Pastry", "Biscuit", "Cake", ""]

arr = str.trim().split(/\s+/);
console.log(arr); //["Chocolate", "Pastry", "Biscuit", "Cake"]

In JavaScript, a regular expression is written inside a pair of slash (/) characters.

\s means any whitespace character. Whitespace character includes space, tab, and new line.

In a regular expression, the plus (+) sign has a special meaning. + matches one or more occurrences of the item preceding it.

Recommended Posts