Up | Split String - A JavaScript Function © 2025 Greg Abbott
/*
Split a string ['Before', 'At', 'After', 'Around']
every occurrence of a regular expression or string delimiter,
infinitely, or into a maximum number of parts.
// EXAMPLE USES ================================================
// AROUND
// The split around mode populates an array with:
// each substring before, between, and after the pattern
// and each occurrence of the text matching the pattern
// It works well with marked up text, parentheses and quotes
// Define a pattern
const text_in_parentheses =
/(^|\s)\([^\s)](?:[^)]*[^\s)])?\)[!?.:;,]?/g
// Optionally make a function for re-use
const split_around_parentheses =
split_string({around: text_in_parentheses, trim: true})
// Use the function
split_around_parentheses(
`before (comment1) middle (comment2) after`
)
// Result
// [`before`,`(comment1)`,`middle`,`(comment2)`,`after`]
// AFTER splits after each occurrence of the pattern
// It adds text matching the pattern to the end of items
split_string({ after: ', ' })('hello, world')
// ['hello, ','world']
// BEFORE splits before each occurrence of the pattern
// It adds text matching the pattern to the start of items
split_string({ before: /\band\b/ })('you and me')
// ['you ','and me']
// AT works like .split() and removes the pattern from the array
split_string({ at: '|' })('a|b|c')
// ['a','b','c'] // ^ All pipes removed
// MAX_PARTS splits a string by a pattern until it has N parts
split_string({ after:',', max_parts: 3 })('a,b,c,d,e')
// ['a,', 'b,', 'c,d,e']
// KEEP_EMPTY allows blank items in the resulting array
split_string({ at:',', keep_empty:true })('a,,b')
// ['a', '', 'b']
// Define splitter functions for use in loops or chains
const split_after_commas = split_string({after:','})
const list = ['x,y,z','a,b,c','d,e,f']
const use_in_loops = list.map(split_after_commas)
// HOOK send each part split_string makes through a function
split_string({at:',',hook:x=>x.toUpperCase()+'!'})(`a,b,c,d`)
//['A!','B!'…]
// ACCUMULATOR
let existing_array = ['a','b']
// Add to existing array
split_string({at:','})(`c,d,e,f`,existing_array)
// Clear existing array and add to it (keep object reference)
split_string({at:','})(`c,d,e,f`,existing_array,true)
*/