Skip to content

Instantly share code, notes, and snippets.

@kjantzer
Last active May 1, 2019 11:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kjantzer/4957176 to your computer and use it in GitHub Desktop.
Save kjantzer/4957176 to your computer and use it in GitHub Desktop.
JavaScript: Plural - create a plural or singluar sentence based on a number
/*
Plural - create singlular or plural sentence based on number given (all numbers but 1 return plural sentence)
var str = "Do you want to delete this? There {are|is} [num] book{s} attached."
var num = 2 // or 0, 3, 4, ...
"Do you want to delete this? There are 2 books attached."
var num = 1
"Do you want to delete this? There is 1 book attached."
*/
plural: function(str, num){
var indx = num == 1 ? 1 : 0;
str = str.replace(/\[num\]/, num);
str = str.replace(/{(.[^}]*)}/g, function(wholematch,firstmatch){
var values = firstmatch.split('|');
return values[indx] || '';
});
return str;
}
/*
PHP Port of Plural.js
*/
public static function plural($str, $num){
$indx = $num == 1 ? 1 : 0;
$str = preg_replace("/\[num\]/", $num, $str);
$str = preg_replace_callback("/{(.[^}]*)}/", function($matches) use($indx){
$values = explode('|', $matches[1]);
return isset($values[$indx]) ? $values[$indx] : '';
}, $str);
return $str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment