JavaScript 将英文字符串复数化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27194359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript pluralize an english string
提问by pmrotule
In PHP, I use Kuwamoto's class to pluralize nouns in my strings. I didn't find something as good as this script in javascript except for some plugins. So, it would be great to have a javascript function based on Kuwamoto's class.
在 PHP 中,我使用 Kuwamoto 的类将字符串中的名词复数。除了一些插件,我没有在 javascript 中找到像这个脚本一样好的东西。所以,如果有一个基于 Kuwamoto 的类的 javascript 函数会很棒。
http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/
http://kuwamoto.org/2007/12/17/improved-pluralizing-in-php-actionscript-and-ror/
回答by sarink
Simple version (ES6):
简单版(ES6):
const maybePluralize = (count, noun, suffix = 's') =>
`${count} ${noun}${count !== 1 ? suffix : ''}`;
Usage:
用法:
maybePluralize(0, 'turtle'); // 0 turtles
maybePluralize(1, 'turtle'); // 1 turtle
maybePluralize(2, 'turtle'); // 2 turtles
maybePluralize(3, 'fox', 'es'); // 3 foxes
This obviously doesn't support all english edge-cases, but it's suitable for most purposes
这显然不支持所有英语边缘情况,但它适用于大多数目的
回答by Joshua Pinter
Use Pluralize
使用复数
There's a great little library called Pluralizethat's packaged in npm and bower.
有一个名为Pluralize的很棒的小库,它打包在 npm 和 bower 中。
This is what it looks like to use:
这是它的使用方式:
import Pluralize from 'pluralize';
Pluralize( 'Towel', 42 ); // "Towels"
Pluralize( 'Towel', 42, true ); // "42 Towels"
And you can get it here:
你可以在这里得到它:
回答by pmrotule
So, I answer my own question by sharing my translation in javascript of Kuwamoto's PHP class.
所以,我通过在 Kuwamoto 的 PHP 类的 javascript 中分享我的翻译来回答我自己的问题。
String.prototype.plural = function(revert){
var plural = {
'(quiz)$' : "zes",
'^(ox)$' : "en",
'([m|l])ouse$' : "ice",
'(matr|vert|ind)ix|ex$' : "ices",
'(x|ch|ss|sh)$' : "es",
'([^aeiouy]|qu)y$' : "ies",
'(hive)$' : "s",
'(?:([^f])fe|([lr])f)$' : "ves",
'(shea|lea|loa|thie)f$' : "ves",
'sis$' : "ses",
'([ti])um$' : "a",
'(tomat|potat|ech|her|vet)o$': "oes",
'(bu)s$' : "ses",
'(alias)$' : "es",
'(octop)us$' : "i",
'(ax|test)is$' : "es",
'(us)$' : "es",
'([^s]+)$' : "s"
};
var singular = {
'(quiz)zes$' : "",
'(matr)ices$' : "ix",
'(vert|ind)ices$' : "ex",
'^(ox)en$' : "",
'(alias)es$' : "",
'(octop|vir)i$' : "us",
'(cris|ax|test)es$' : "is",
'(shoe)s$' : "",
'(o)es$' : "",
'(bus)es$' : "",
'([m|l])ice$' : "ouse",
'(x|ch|ss|sh)es$' : "",
'(m)ovies$' : "ovie",
'(s)eries$' : "eries",
'([^aeiouy]|qu)ies$' : "y",
'([lr])ves$' : "f",
'(tive)s$' : "",
'(hive)s$' : "",
'(li|wi|kni)ves$' : "fe",
'(shea|loa|lea|thie)ves$': "f",
'(^analy)ses$' : "sis",
'((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$': "sis",
'([ti])a$' : "um",
'(n)ews$' : "ews",
'(h|bl)ouses$' : "ouse",
'(corpse)s$' : "",
'(us)es$' : "",
's$' : ""
};
var irregular = {
'move' : 'moves',
'foot' : 'feet',
'goose' : 'geese',
'sex' : 'sexes',
'child' : 'children',
'man' : 'men',
'tooth' : 'teeth',
'person' : 'people'
};
var uncountable = [
'sheep',
'fish',
'deer',
'moose',
'series',
'species',
'money',
'rice',
'information',
'equipment'
];
// save some time in the case that singular and plural are the same
if(uncountable.indexOf(this.toLowerCase()) >= 0)
return this;
// check for irregular forms
for(word in irregular){
if(revert){
var pattern = new RegExp(irregular[word]+'$', 'i');
var replace = word;
} else{ var pattern = new RegExp(word+'$', 'i');
var replace = irregular[word];
}
if(pattern.test(this))
return this.replace(pattern, replace);
}
if(revert) var array = singular;
else var array = plural;
// check for matches using regular expressions
for(reg in array){
var pattern = new RegExp(reg, 'i');
if(pattern.test(this))
return this.replace(pattern, array[reg]);
}
return this;
}
Easy to use:
便于使用:
alert("page".plural()); // return plural form => pages
alert("mouse".plural()); // return plural form => mice
alert("women".plural(true)); // return singular form => woman
回答by Sergio Tapia
Taken from my blog: https://sergiotapia.me/pluralizing-strings-in-javascript-es6-b5d4d651d403
摘自我的博客:https: //sergiotapia.me/pluralizing-strings-in-javascript-es6-b5d4d651d403
You can use the pluralizelibrary for this.
您可以为此使用复数库。
NPM:
npm install pluralize --save
Yarn:
yarn add pluralize
Wherever you want to use the lib, you can require it easily.
无论您想在何处使用该库,都可以轻松地使用它。
var pluralize = require('pluralize')
I like to add it to the window object so I can just invoke pluralize() wherever I need it. Within my application.js root file:
我喜欢将它添加到 window 对象,这样我就可以在需要的地方调用 Multipleize() 。在我的 application.js 根文件中:
window.pluralize = require('pluralize')
Then you can just use it anywhere, React components, or just plain Javascript:
然后你就可以在任何地方使用它,React 组件,或者只是简单的 Javascript:
<span className="pull-left">
{`${item.score} ${pluralize('point', item.score)}`}
</span>
console.log(pluralize('point', item.score))
回答by gasolin
The new intl API spec from ECMA will provide the plural rules function, https://github.com/tc39/proposal-intl-plural-rules
ECMA 的新国际 API 规范将提供复数规则功能, https://github.com/tc39/proposal-intl-plural-rules
Here's the polyfill that can be used today https://github.com/eemeli/IntlPluralRules
下面是今天可以使用的 polyfill https://github.com/eemeli/IntlPluralRules
回答by Erik Campobadal
Based on @pmrotule answer with some typescript magic and some additions to the uncountable array. I add here the plural and singular functions.
基于@pmrotule 答案,带有一些打字稿魔法和对不可数数组的一些补充。我在这里添加复数和单数功能。
The plural version:
复数版本:
/**
* Returns the plural of an English word.
*
* @export
* @param {string} word
* @param {number} [amount]
* @returns {string}
*/
export function plural(word: string, amount?: number): string {
if (amount !== undefined && amount === 1) {
return word
}
const plural: { [key: string]: string } = {
'(quiz)$' : "zes",
'^(ox)$' : "en",
'([m|l])ouse$' : "ice",
'(matr|vert|ind)ix|ex$' : "ices",
'(x|ch|ss|sh)$' : "es",
'([^aeiouy]|qu)y$' : "ies",
'(hive)$' : "s",
'(?:([^f])fe|([lr])f)$' : "ves",
'(shea|lea|loa|thie)f$' : "ves",
'sis$' : "ses",
'([ti])um$' : "a",
'(tomat|potat|ech|her|vet)o$': "oes",
'(bu)s$' : "ses",
'(alias)$' : "es",
'(octop)us$' : "i",
'(ax|test)is$' : "es",
'(us)$' : "es",
'([^s]+)$' : "s"
}
const irregular: { [key: string]: string } = {
'move' : 'moves',
'foot' : 'feet',
'goose' : 'geese',
'sex' : 'sexes',
'child' : 'children',
'man' : 'men',
'tooth' : 'teeth',
'person' : 'people'
}
const uncountable: string[] = [
'sheep',
'fish',
'deer',
'moose',
'series',
'species',
'money',
'rice',
'information',
'equipment',
'bison',
'cod',
'offspring',
'pike',
'salmon',
'shrimp',
'swine',
'trout',
'aircraft',
'hovercraft',
'spacecraft',
'sugar',
'tuna',
'you',
'wood'
]
// save some time in the case that singular and plural are the same
if (uncountable.indexOf(word.toLowerCase()) >= 0) {
return word
}
// check for irregular forms
for (const w in irregular) {
const pattern = new RegExp(`${w}$`, 'i')
const replace = irregular[w]
if (pattern.test(word)) {
return word.replace(pattern, replace)
}
}
// check for matches using regular expressions
for (const reg in plural) {
const pattern = new RegExp(reg, 'i')
if (pattern.test(word)) {
return word.replace(pattern, plural[reg])
}
}
return word
}
And the singular version:
和单数版本:
/**
* Returns the singular of an English word.
*
* @export
* @param {string} word
* @param {number} [amount]
* @returns {string}
*/
export function singular(word: string, amount?: number): string {
if (amount !== undefined && amount !== 1) {
return word
}
const singular: { [key: string]: string } = {
'(quiz)zes$' : "",
'(matr)ices$' : "ix",
'(vert|ind)ices$' : "ex",
'^(ox)en$' : "",
'(alias)es$' : "",
'(octop|vir)i$' : "us",
'(cris|ax|test)es$' : "is",
'(shoe)s$' : "",
'(o)es$' : "",
'(bus)es$' : "",
'([m|l])ice$' : "ouse",
'(x|ch|ss|sh)es$' : "",
'(m)ovies$' : "ovie",
'(s)eries$' : "eries",
'([^aeiouy]|qu)ies$' : "y",
'([lr])ves$' : "f",
'(tive)s$' : "",
'(hive)s$' : "",
'(li|wi|kni)ves$' : "fe",
'(shea|loa|lea|thie)ves$': "f",
'(^analy)ses$' : "sis",
'((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$': "sis",
'([ti])a$' : "um",
'(n)ews$' : "ews",
'(h|bl)ouses$' : "ouse",
'(corpse)s$' : "",
'(us)es$' : "",
's$' : ""
}
const irregular: { [key: string]: string } = {
'move' : 'moves',
'foot' : 'feet',
'goose' : 'geese',
'sex' : 'sexes',
'child' : 'children',
'man' : 'men',
'tooth' : 'teeth',
'person' : 'people'
}
const uncountable: string[] = [
'sheep',
'fish',
'deer',
'moose',
'series',
'species',
'money',
'rice',
'information',
'equipment',
'bison',
'cod',
'offspring',
'pike',
'salmon',
'shrimp',
'swine',
'trout',
'aircraft',
'hovercraft',
'spacecraft',
'sugar',
'tuna',
'you',
'wood'
]
// save some time in the case that singular and plural are the same
if (uncountable.indexOf(word.toLowerCase()) >= 0) {
return word
}
// check for irregular forms
for (const w in irregular) {
const pattern = new RegExp(`${irregular[w]}$`, 'i')
const replace = w
if (pattern.test(word)) {
return word.replace(pattern, replace)
}
}
// check for matches using regular expressions
for (const reg in singular) {
const pattern = new RegExp(reg, 'i')
if (pattern.test(word)) {
return word.replace(pattern, singular[reg])
}
}
return word
}
回答by Tudor Morar
I use this simple inline statement
我使用这个简单的内联语句
const number = 2;
const string = `${number} trutle${number === 1 ? "" : "s"}`; //this one
console.log(string)
回答by Slava Fomin II
I've created a very simple library that can be used for words pluralization in JavaScript. It transparently uses CLDR database for multiple locales, so it supports almost any language you would like to use. It's API is very minimalistic and integration is extremely simple. It's called Numerous.
我创建了一个非常简单的库,可用于 JavaScript 中的单词复数。它透明地将 CLDR 数据库用于多种语言环境,因此它几乎支持您想使用的任何语言。它的 API 非常简约,集成非常简单。它被称为无数。
I've also written a small introduction article to it: ?How to pluralize any word in different languages using JavaScript??.
我还写了一篇关于它的小介绍文章: ? 如何使用 JavaScript 将不同语言中的任何单词复数化??.
Feel free to use it in your project. I will also be glad for your feedback on it.
随意在您的项目中使用它。我也很高兴收到您的反馈。
回答by barncat
function pluralize( /* n, [ n2, n3, ... ] str */ ) {
var n = Array.prototype.slice.call( arguments ) ;
var str = n.pop(), iMax = n.length - 1, i = -1, j ;
str = str.replace( /$$|$(\d+)/g,
function( m, p1 ) { return m == '$$' ? '$' : n[+p1-1] }
) ;
return str.replace( /[(](.*?)([+-])(\d*)(?:,([^,)]*))?(?:,([^)]*))?[)]/g,
function( match, one, sign, abs, not1, zero ) {
// if abs, use indicated element in the array of numbers
// instead of using the next element in sequence
abs ? ( j = +abs - 1 ) : ( i < iMax && i++, j = i ) ;
if ( zero != undefined && n[j] == 0 ) return zero ;
return ( n[j] != 1 ) == ( sign == '+' ) ? ( not1 || 's' ) : one ;
}
) ;
}
console.log( pluralize( 1, 'the cat(+) live(-) outside' ) ) ;
// the cat lives outside
console.log( pluralize( 2, 'the child(+,ren) (is+,are) inside' ) ) ;
// the children are inside
console.log( pluralize( 0, ' dog(+), (+,,no) dog(+), (+,,no) dog(+,,)' ) ) ;
// 0 dogs, no dogs, no dog
console.log( pluralize( 100, 1, ' penn(y+,ies) make(-1) $$' ) ) ;
// 100 pennies make
console.log( pluralize( 1, 0.01, ' penn(y+,ies) make(-1) $$' ) ) ;
// 1 penny makes // Function to create a string from given key value pairs and pluralize keys
const stringPluralize = function(data){
var suffix = 's';
var str = '';
$.each(data, function(key, val){
if(str != ''){
str += val>0 ? ` and ${val} ${key}${val !== 1 ? suffix : ''}` : '';
}
else{
str = val>0 ? `${val} ${key}${val !== 1 ? suffix : ''}` : '';
}
});
return str;
}
var leftDays = '1';
var leftHours = '12';
var str = stringPluralize({day:leftDays, hour:leftHours});
console.log(str) // Gives 1 day and 12 hours
.01
回答by Chintan Bhatt
Using @sarink's answer, I made a function to create a string using key value pairs data and pluralizing the keys. Here's the snippet:
使用@sarink 的回答,我创建了一个函数来使用键值对数据和复数键来创建一个字符串。这是片段:
##代码##
