Splitting strings by lengths

JavaScript can split strings at given characters. By matching against a regular expression, we can split strings into substrings of a given length instead.

// split at every `O`; all `O`s are gone in the result
'BRBIDKLOLOMGOK'.split('O')  // ⇒ ['BRBIDKL', 'L', 'MG', 'K']

// split into groups of up to 3 characters (the last group can be shorter)
'BRBIDKLOLOMGOK'.match(/.{1,3}/g)  // ⇒ ['BRB', 'IDK', 'LOL', 'OMG', 'OK']

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.