This post will discuss how to split a string into substrings based on a delimiter in JavaScript.

A delimiter is a character or a string that defines where to split the string. To split a string based on a delimiter in JavaScript, we need to use some function or function that can separate the string into an array of substrings based on the delimiter. Here are some of the most common and easy-to-use functions for splitting a string based on a given delimiter in JavaScript:

1. Using String.split() function

The split() is an instance function of the String object that splits a string into an array of substrings based on a separator. The separator can be a string or a regular expression that defines where to split the string. For example, if we want to split the string "Hello world!" using space (" ") as the delimiter, we can write:

Download  Run Code

 
We can also use an empty string ("") as the delimiter to split the string into individual characters. Here’s an example:

Download  Run Code

 
We can also use multiple delimiters by passing a regular expression that contains them. For example, if we want to split a string by commas or spaces, we can do something like this:

Download  Run Code

2. Using String.match() function

The match() is another instance function of the String object that matches a string against a regular expression and returns an array of the matched substrings. The regular expression can define what kind of substrings to match, such as letters, digits, symbols, or patterns. For example, if we want to split the string "Hello world!" using any non-alphanumeric character (\W) as the delimiter, we can write:

Download  Run Code

 
We can also use parentheses () in the regular expression to capture the delimiters as well as the substrings. Here’s an example:

Download  Run Code

3. Using String.replace() function

The replace() is a third instance function of the String object that replaces a substring or a regular expression with another string or a function. We can use this function to split a string by replacing the delimiters with some special characters, such as commas or brackets, and then parsing the resulting string into an array. For example, if we want to split the string "Hello world!" using space (" ") as the delimiter, we can write:

Download  Run Code

 
We can also use parentheses () in the regular expression to capture the delimiters and include them in the array. Here’s an example:

Download  Run Code

That’s all about splitting a string into substrings based on a delimiter in JavaScript.