Javascript String splitBy(delimiter)

Description

Javascript String splitBy(delimiter)


String.prototype.splitBy = function (delimiter) {
  var //from w  ww .j av a  2 s.  c o m
    delimiterPATTERN = '(' + delimiter + ')', 
    delimiterRE = new RegExp(delimiterPATTERN, 'g');
  
  return this.split(delimiterRE).reduce((chunks, item) => {
    if (item.match(delimiterRE)){
      chunks.push(item)
    } else {
      chunks[chunks.length - 1] += item
    };
    return chunks
  }, [])
}



PreviousNext

Related