Fraser Hamilton

How to split a string in JavaScript

November 05, 2021

In Javascirpt the split method can be used to divide a stirng into an array of substrings. The split will be performed based on a separtor that is passed to the function.

Here’s a classic example of how to split a comma spearated list of values using the , character as a separator.

const list = '1, 3, 5, 6'

const split = list.split(',')


// ['1', ' 3', ' 5', ' 6']

However we’re not limited to splitting only on a single character we can also do so based on a substring or regular expression. The regular expression used in the second example below matches capital letters.

const intro = 'Hello There My Name Is Fraser Hamilton'

const split = intro.split('am')


// ['Hello There My N', 'e Is Fraser H', 'ilton']

const splitReg = intro.split(/(?=[A-Z])/)


// ['Hello ', 'There ', 'My ', 'Name ', 'Is ', 'Fraser ', 'Hamilton']

Written by Fraser Hamilton a full stack developer based out of Edinburgh, Scotland.

© 2021, Fraser Hamilton