DEV Community

Dillion Megida
Dillion Megida

Posted on

String.split() in Javascript

split is a method used on strings to as the name implies, break the string at the specified breakpoint. The pieces are converted to values in an array.

Syntax

'string'.split(breakPoint);
Enter fullscreen mode Exit fullscreen mode

split looks for a point in a string that matches the breakPoint provided, and at those points splits the string.

Return value

The returned value is an array whose values are the pieces of the broken string.

Format of breakpoints

Breakpoints allow two formats: strings and regex. Let's see them in action.

String breakpoints

Example 1

const str = 'String.split() in Javascript article, (yeah'
const pieces = str.split('(');
console.log(pieces);
// Expected output
// [ 'String.split', ') in Javascript article, ', 'yeah' ]
Enter fullscreen mode Exit fullscreen mode

As you'd notice, the string is broken at points which matches '('. You'd also notice that the pieces do not contain this value anymore. You can think of it like this: split replaces the breakpoints with a break.

Example 2

const str = 'String.split() in Javascript article'
const pieces = str.split(' ');
console.log(pieces)
// Expected output
// [ 'String.split()', 'in', 'Javascript', 'article' ]
Enter fullscreen mode Exit fullscreen mode

As seen above, the spaces (' ') are replaced with breaks

RegExp breakpoints

Just like string breakpoints, split breaks the strings at points that matches the regex.

Example 1

const str = 'String.split() in 1b in 1c in Javascript article'
const regex = /\d{1}.{1}/
const pieces = str.split(regex);
console.log(pieces)
// Expected output
// [ 'String.split() in ', ' in ', ' in Javascript article' ]
Enter fullscreen mode Exit fullscreen mode

The regex matches strings with one number (\d{1}) and one character (.{.{1}), hence those points are replaced with breakpoints. We can't use string breakpoints for such cases because of the various combinations of letters and characters.

Example 2

const str = 'String.split() in 1b in 1c in Javascript article'
const pieces = str.split(/.{2}in.{2}/);
console.log(pieces)
// Expected output
// [ 'S', 'split(', '', '', 'avascript article' ]
Enter fullscreen mode Exit fullscreen mode

The regex matches points that begin with two characters and ends with two characters with the string 'in' in-between. Points 'tring.', ') in 1', 'b in 1' and 'c in J' matches the regex and the string is broken at those points.

Wrap Up

The best breakpoint to use depends on your use case. If you want to be overly specific, string breakpoints are easy to use. Regex breakpoints come with a bit of complexity but very effective.

Thanks for reading : )

Top comments (0)