Let's assume that you declare the following string:
javascriptlet 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:
Separate the chars with a bar |
:
javascriptlet 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", "."]
Add a backslash \
before the special characters:
javascriptlet 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", ""]
javascriptlet 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", "", ""]
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:
javascriptlet 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.