a8m / angular-filter

Bunch of useful filters for AngularJS (with no external dependencies!)
https://github.com/a8m/angular-filter
MIT License
2.93k stars 332 forks source link

'split' filter for string to transform it as Array? #241

Closed marchrius closed 7 years ago

marchrius commented 7 years ago

An example:

angular.module('app').filter('split', splitFilterFactory);
function splitFilterFactory() {
  return function splitAfterN(stringToSplit, splitString, afterN) {
    afterN = angular.isNumber(afterN) && afterN >= 0 ? afterN : 0;
    var retArray = (stringToSplit || '').split((splitString || ''));
    if (afterN > 0 && afterN <= retArray.length) {
      var splitted = [retArray.splice(0, afterN), retArray.splice(0)];
      retArray.push(splitted[0].join(splitString));
      retArray.push.apply(retArray, splitted[1]);
    }
    return retArray;
  }
}

EDIT using regexp

angular.module('app').filter('split', splitFilterFactory);
function splitFilterFactory() {
  return function splitAfterN(stringToSplit, splitString, afterN) {
    afterN = angular.isNumber(afterN) && afterN >= 0 ? afterN : 0;
    splitString = splitString || '';
    var regexp = new RegExp(splitString, "g"),
          numberOfSplitString = stringToSplit.match(regexp).length,
          skip = stringToSplit.length / numberOfSplitString * afterN;
    if (afterN >= numberOfSplitString) {
      return [stringToSplit];
    }
    skip = stringToSplit.indexOf(splitString, skip);
    var retArray = stringToSplit.substr(skip).split(splitString);
    retArray.splice(0, 1, stringToSplit.substr(0, skip));
    return retArray;
  }
}
a8m commented 7 years ago

Hey @Marchrius, Can you please give us a short description what is it? Is it a new filter suggestion?

marchrius commented 7 years ago

@a8m exactly! As the title says, it's a filter to split string into array.

This is a plunker example https://plnkr.co/edit/pT4XlTnD7sIJhzqkyx5A

a8m commented 7 years ago

Closed via v0.5.15