Splitting by a Simple Pattern

Using a simple regular expression pattern to split a string. This can be a single character or a set of characters.

Example: It demonstrates how to split a string of fruits by commas into an array using a regular expression as the separator.

JavaScript
let str = "apple,banana,cherry";
let result = str.split(/,/);
console.log(result);

Output
[ 'apple', 'banana', 'cherry' ]

JavaScript String.Split() Example with RegEx

The String.split() method in JavaScript is used to split a string into an array of substrings based on a specified delimiter. When a regular expression (RegEx) is used as the delimiter, it allows for more complex and powerful splitting criteria. This is particularly useful for splitting strings based on patterns rather than static characters. By leveraging regular expressions, you can handle various splitting scenarios, such as splitting by multiple delimiters, ignoring certain patterns, or capturing groups of characters.

Similar Reads

Syntax

The basic syntax for the split() method using a RegEx is:...

Splitting by a Simple Pattern

Using a simple regular expression pattern to split a string. This can be a single character or a set of characters....

Splitting by Multiple Delimiters

Using a RegEx pattern to split a string by multiple delimiters. This can include spaces, commas, semicolons, etc....

Ignoring Specific Patterns

Using a RegEx pattern to split a string while ignoring certain patterns, such as sequences of spaces....