Port of ActiveSupport::Inflector::Inflections for underscore.js
Port of ActiveSupport::Inflector::Inflections for Underscore.js.
Works with browser or Node.js.
I created this underscore mixin after trying out every other inflection library out there. I've created this as a direct port of Rails' version as much as possible.
Note that right now, this only handles methods found in ActiveSupport::Inflector::Inflections since that's all I need right now. I may eventually split this out into separate inflector mixins that match all of ActiveSupport's.
Include both underscore.js and underscore.inflections on your page:
First, install the mixin through npm:
npm install underscore.inflections
Require underscore.js and underscore.inflections:
var _ = require'underscore';_mixinrequire'underscore.inflections';
Note: When using underscore in Node's REPL, be sure to choose a variable other than
_, as that is a special symbol used for showing the last return value.
Converts a word to its singular form.
_singularize'posts'; //=> 'post'_singularize'octopi'; //=> 'octopus'_singularize'sheep'; //=> 'sheep'_singularize'words'; //=> 'words'
Converts a word to its pluralized form.
_pluralize'post'; //=> 'posts'_pluralize'octopus'; //=> 'octopi'_pluralize'sheep'; //=> 'sheep'_pluralize'words'; //=> 'words'
Adds a rule for singularizing a word.
Adds a rule for pluralizing a word.
Adds a rule for an irregular word.
Adds a rule for an uncountable word or words.
Makes the following inflection methods aware of acronyms: _.camelize, _.underscore, _.humanize, _.titleize See inflections_test for a full specifications of the subtleties
_acronym"FBI";_camelize"fbi_file"; //=> 'FBIFile'_underscore"FBIFile"; //=> 'fbi_file'
_camelize'make_me_tall'; //=> 'MakeMeTall'
When passed false as second parameter it does not capitalize the first word
_camelize'make_me_tall' false; //=> 'makeMeTall'
Separate camel cased strings with underscores
_underscore'INeedSomeSpace'; //=> 'i_need_some_space'
Format underscored strings for human friendly consumption
_humanize'i_just_want_to_be_understood'; //=> 'I just want to be understood'
You can also add humanizing rules by calling
_human/_cnt$/'_count';_humanize'jargon_cnt'; //=> 'Jargon count'
Title case a underscored or camel cased string
_titleize'three_blind_mice'; //=> 'Three Blind Mice'_titleize'JackAndJill'; //=> 'Jack And Jill'