Keep symbols in the array when splitting string

Let's assume that you have the following sentece:

javascript
let sentence = 'Erik is an engineer. He is from Barcelona, Spain.'

If you want to split the sentence by the punctuation marks:

javascript

let arr = sentence.split(/\.|\,/)

// Using split removes special symbols
// ["Erik is an engineer", " He is from Barcelona", " Spain", ""]

Add parenthesis to include the separators:

javascript
let arr = sentence.split(/(\.|\,)/)

// ["Erik is an engineer", ".", " He is from Barcelona", ",", " Spain", ".", ""]

You may notice an empty string at the end (because of the period). You can delete it by filtering:

javascript
let arr = sentence.split(/(\.|\,)/).filter(e => e !== '')

// ["Erik is an engineer", ".", " He is from Barcelona", ",", " Spain", "."]

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