JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 686
  • Score
    100M100P100Q99547F
  • License MIT

Improved Javascript string split, for handling RegExp in a way that can easily re-create the original string

Package Exports

  • smart-split

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (smart-split) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

smart-split

The default String.prototype.split() function behaves very differently for String and RegExp inputs. smart-split normalizes that behavior.

Installation

npm install smart-split

Usage

var split = require('smart-split')

split(input, splitOn)

Differences with String.prototype.split()

smart-split will always return the split portions of the string, interspersed with the split-on portions of the string.

split('a b c', ' ')   // ['a', ' ', 'b', ' ', 'c']
split('a bxc', / |x/) // ['a', ' ', 'b', 'x', 'c']
'a b c'.split(' ')    // ['a', 'b', 'c']
'a bxc'.split(/ |x/)  // ['a', 'b', 'c']

String.prototype.split() has weird behavior with matching parentheses, which makes predicting the output for unknown RegExp input difficult. smart-split ignores matching parens, and always outputs the full matched string.

split('a b c', / /)     // ['a', ' ', 'b', ' ', 'c']
split('a b c', /( )/)   // ['a', ' ', 'b', ' ', 'c']
split('a b c', /( )()/) // ['a', ' ', 'b', ' ', 'c']
'a b c'.split(/ /)      // ['a', 'b', 'c']
'a b c'.split(/( )/)    // ['a', ' ', 'b', ' ', 'c']
'a b c'.split(/( ())/)  // ['a', ' ', '', 'b', ' ', '', 'c']

These two features mean:

  • split(input, x).join() === input, which is useful for reconstructing the original string from the split version.
  • Whatever the input is, the even indicies (0,2,4...) will always contain the split input, and the odd indicies (1, 3...) will have the splitters.