How to Split a String by a Specified Delimiter in JavaScript

08/01/2021

Contents

In this article, you will learn how to get started with Anime.js.

Splitting a string by a specified delimiter in JavaScript

Splitting a string by a specified delimiter is a common task in JavaScript. There are several ways to split a string by a specified delimiter.

Using the split() method

The split() method is a built-in method in JavaScript that splits a string into an array of substrings based on a specified delimiter. Here’s how you can use it:

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

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

Using the substring() method

The substring() method is another built-in method in JavaScript that can be used to split a string by a specified delimiter. Here’s how you can use it:

const str = "apple,banana,orange";
const delimiter = ",";
const arr = [];

let start = 0;
let end = str.indexOf(delimiter);

while (end !== -1) {
  arr.push(str.substring(start, end));
  start = end + delimiter.length;
  end = str.indexOf(delimiter, start);
}

arr.push(str.substring(start));
console.log(arr); // ["apple", "banana", "orange"]

In this example, we used a while loop to find each occurrence of the delimiter and push the substring between the previous occurrence and the current occurrence into an array.

Using a regular expression

You can also use a regular expression to split a string by a specified delimiter. Here’s how you can use it:

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

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

Using the match() method

The match() method is a built-in method in JavaScript that can be used to split a string by a specified delimiter using a regular expression. Here’s how you can use it:

const str = "apple,banana,orange";
const arr = str.match(/[^,]+/g);
console.log(arr); // ["apple", "banana", "orange"]

In this example, we used the regular expression /[^,]+/g to match any sequence of characters that is not a comma and split the string into an array of substrings [“apple”, “banana”, “orange”].