JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to split a string with multiple separators in JavaScript?

In general, commas, hyphens, and underscores are used as separators. So, if a string has multiple separators and you want to split that string on those separators, then pass a regular expression, i.e., [,\-_]+ to the split() method.

let str = "Doughnut-Pie_Cupcake,Pastry";
let arr = str.split(/[,\-_]+/);

console.log(arr); //["Doughnut", "Pie", "Cupcake", "Pastry"]

Here is the explanation of the code:

1. The string in this example has multiple separators.

let str = "Doughnut-Pie_Cupcake,Pastry";

2. A regular expression is passed to the split() method. In JavaScript, a pair of slash characters are used to define the regular expression. Square brackets are called character class, and it matches any one of the characters defined inside it. Inside the character class, a hyphen is used to describe the range of characters, so to match a hyphen, you have to escape it with a backslash.

+ sign matches one or more than one occurrence of the item defined before it. In this example, the previous item is a character class, so the plus sign matches one or more occurrences of the comma, hyphen, and underscore.

let arr = str.split(/[,\-_]+/);

console.log(arr); //["Doughnut", "Pie", "Cupcake", "Pastry"]

Recommended Posts