JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to split a string by comma or space in JavaScript?

In this tutorial, you will learn how to split a string by comma or space.

When you pass a regular expression, i.e., /[, ]+/, to the split() method, it will split a string on space or comma and returns an array of substrings.

let str = "React, Angular, Vue";

let result = str.split(/[, ]+/);
console.log(result); //["React", "Angular", "Vue"]

You pass a separator in the form of a string or regular expression to the split() method.

The regular expression is specified by enclosing them in a pair of slash characters (/).

In a regular expression, the square brackets [] are called character class and match any one of the letters written inside them. In this case, it will match either space or comma.

The plus (+) sign matches one or more occurrences of the preceding item. In this case, a comma and a space placed next to each other will be considered a match.

The regular expression /[, ]+/ will match the following:

  • One or more than one commas, e.g., "React,Angular,,,,Vue"
  • One or multiple spaces, e.g., "React     Angular Vue"
  • Any combination of comma and space. e.g., "React, Angular,,,, Vue"
let str = "React,Angular,,,,Vue";

let result = str.split(/[, ]+/);
console.log(result); //["React", "Angular", "Vue"]

str = "React     Angular Vue";
result = str.split(/[, ]+/);
console.log(result); //["React", "Angular", "Vue"]

str = "React,   Angular,,,, Vue";
result = str.split(/[, ]+/);
console.log(result); //["React", "Angular", "Vue"]

You might find a situation where a string ends in a space or comma. In that case, calling the split() method returns an empty string.

let str = "React, Angular, Vue, ";

let arr = str.split(/[, ]+/);
console.log(arr); //["React", "Angular", "Vue", ""]

To get rid of it, use the array filter() method. Inside the callback function of the filter() method returns false for the empty element, and in this way, you can filter out empty strings.

let str = "React, Angular, Vue, ";

let arr = str.split(/[, ]+/).filter(element => element);
console.log(arr); //["React", "Angular", "Vue"]

Recommended Posts