Split by multiple characters in JavaScript

Let's assume that you declare the following string:

javascript
let str = `Hello, my name is Erik. I'm from Barcelona, Spain.`;

If you want to split the sentence into an array with multiple chars as separators:

Normal chars

Separate the chars with a bar |:

javascript
let str = `Hello, my name is Erik. I'm from Barcelona, Spain.`;

let res = str.split(/a|n/);
// ["Hello, my ", "", "me is Erik. I'm from B", "rcelo", "", ", Sp", "i", "."]

Specials chars

Add a backslash \ before the special characters:

javascript
let str = `Hello, my name is Erik. I'm from Barcelona, Spain.`;

let res = str.split(/\.|\,/);
// ["Hello", " my name is Erik", " I'm from Barcelona", " Spain", ""]

Combination of both

javascript
let str = `Hello, my name is Erik. I'm from Barcelona, Spain.`;

let sep = ['a', 'n', '.', ','];

let reg = sep.map(e => e.match(/[a-zA-Z0-9]/) ? e : `\\${e}`).join('|');

let res = str.split(new RegExp(reg));
//  ["Hello", " my ", "", "me is Erik", " I'm from B", "rcelo", "", "", " Sp", "i", "", ""]

Alernative using reduce()

Here is an alternative using a reduce():

javascript
// Defining the separators
let separators = ['.', ','];

// Replacing the separators with a common separator
// In this case, a sharp knife
let replaced = separators.reduce((acc, separator) => {
    
    acc = acc.replaceAll(separator, '🔪');
    
    return acc;
    
}, str);

// Splitting the string by the sharp knife
let res = replaced.split('🔪');

In one line of code:

javascript
let res = ['.', ','].reduce((acc, separator) => (acc = acc.replaceAll(separator, '🔪'), acc), str).split('🔪');
// ["Hello", " my name is Erik", " I'm from Barcelona", " Spain", ""]

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.