Last active
May 1, 2019 11:47
-
-
Save kjantzer/4957176 to your computer and use it in GitHub Desktop.
JavaScript: Plural - create a plural or singluar sentence based on a number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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