驼峰、下划线、单复数、表名-类名转换...通通交给字符串处理库:i
发布于 7 年前 作者 wxs77577 2314 次浏览 来自 分享

经常会有字符串转换处理的场景,比如一个实体user,对应的Restful资源名是复数users,数据库表名也是users,模型类名可能是User等等,这就需要一个方便的npm包,名字有点奇怪,不过它就是一个单字母:i npm: https://www.npmjs.com/package/i

安装

cnpm install i --save

使用

不一一列举了,看名字就知道了

var inflect = require('i')();
var inflect = require('i')(true); 
//如果是传一个`true`的话就相当于这些方法都加在了String.prototype上,所有的字符串都可以直接用这些方法。
//'messages to store'.titleize // === 'Messages To Store' 

Pluralize

inflect.pluralize('person'); // === 'people'
inflect.pluralize('octopus'); // === 'octopi'
inflect.pluralize('Hat'); // === 'Hats'

Singularize

inflect.singularize('people'); // === 'person'
inflect.singularize('octopi'); // === 'octopus'
inflect.singularize('Hats'); // === 'Hat'

Camelize

inflect.camelize('message_properties'); // === 'MessageProperties'
inflect.camelize('message_properties', false); // === 'messageProperties'

Underscore

inflect.underscore('MessageProperties'); // === 'message_properties'
inflect.underscore('messageProperties'); // === 'message_properties'

Humanize

inflect.humanize('message_id'); // === 'Message'

Dasherize

inflect.dasherize('message_properties'); // === 'message-properties'
inflect.dasherize('Message Properties'); // === 'Message Properties'

Titleize

inflect.titleize('message_properties'); // === 'Message Properties'
inflect.titleize('message properties to keep'); // === 'Message Properties to Keep'

Demodulize

inflect.demodulize('Message.Bus.Properties'); // === 'Properties'

Tableize

inflect.tableize('MessageBusProperty'); // === 'message_bus_properties'

Classify

inflect.classify('message_bus_properties'); // === 'MessageBusProperty'

Foreign key

inflect.foreign_key('MessageBusProperty'); // === 'message_bus_property_id'
inflect.foreign_key('MessageBusProperty', false); // === 'message_bus_propertyid'

Ordinalize

inflect.ordinalize( '1' ); // === '1st'

自定义规则

Custom plural

可以使用正则表达式来定义

inflect.inflections.plural('person', 'guys');
inflect.pluralize('person'); // === 'guys'
inflect.singularize('guys'); // === 'guy'

Custom singular

inflect.inflections.singular('guys', 'person')
inflect.singularize('guys'); // === 'person'
inflect.pluralize('person'); // === 'people'

Custom irregular

inflect.inflections.irregular('person', 'guys')
inflect.pluralize('person'); // === 'guys'
inflect.singularize('guys'); // === 'person'

Custom human

inflect.inflections.human(/^(.*)_cnt$/i, '$1_count');
inflect.inflections.humanize('jargon_cnt'); // === 'Jargon count'

Custom uncountable

inflect.inflections.uncountable('oil')
inflect.pluralize('oil'); // === 'oil'
inflect.singularize('oil'); // === 'oil'

就这样吧。

原文: https://adonis-china.org/posts/11

回到顶部