How to Use the String split() Method in JavaScript

08/01/2021

Contents

In this article, you will learn how to use the string split() method in JavaScript.

Using the string split() method in JavaScript

The split() method in JavaScript is a built-in method that is used to split a string into an array of substrings based on a specified delimiter. This method can be particularly useful when working with large strings that need to be separated into smaller parts.

Syntax

The basic syntax of the split() method is as follows:

string.split(separator, limit);

Parameters

  • separator (required): This parameter specifies the delimiter that is used to split the string into an array of substrings. It can be a string, a regular expression, or a special character. If the separator is an empty string (“”) or a regular expression that matches an empty string, the string will be split into an array of individual characters.
  • limit (optional): This parameter specifies the maximum number of substrings that can be returned in the resulting array. If this parameter is not specified, all substrings will be returned.

Examples

Split a string using a space as a delimiter

const str = "Hello World";
const arr = str.split(" ");
console.log(arr); // ["Hello", "World"]

In this example, we used a space (” “) as the delimiter to split the string “Hello World” into an array of substrings [“Hello”, “World”].

Split a string using a comma as a delimiter

const str = "apple,banana,orange";
const arr = str.split(",");
console.log(arr); // ["apple", "banana", "orange"]

In this example, we used a comma (“,”) as the delimiter to split the string “apple,banana,orange” into an array of substrings [“apple”, “banana”, “orange”].

Split a string using a regular expression as a delimiter

const str = "a1b2c3d4";
const arr = str.split(/\d/);
console.log(arr); // ["a", "b", "c", "d", ""]

In this example, we used the regular expression /\d/ as the delimiter to split the string “a1b2c3d4” into an array of substrings [“a”, “b”, “c”, “d”, “”].

Limit the number of substrings returned

const str = "a,b,c,d,e,f,g,h,i,j";
const arr = str.split(",", 5);
console.log(arr); // ["a", "b", "c", "d", "e"]

In this example, we used a comma (“,”) as the delimiter to split the string “a,b,c,d,e,f,g,h,i,j” into an array of substrings, but limited the number of substrings returned to 5. The resulting array is [“a”, “b”, “c”, “d”, “e”].