Skip to content
This repository has been archived by the owner on Dec 17, 2022. It is now read-only.

brandonhorst/smart-split

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

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

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published