Leandro Vieira Pinho´s Blog

Just another WordPress weblog

Função JavaScript para exibir uma string em singular ou plural

January 7th, 2008. Published under javascript. 4 Comments.

Chegou a vez do JavaScript, após criar um Plugin Smarty para exibir uma string em singular ou plural e uma função PHP com o mesmo propósito, demonstro agora a mesma função em JavaScript.

Segue o código da função:

/**
 * Shows a singular or plural message based in a informed number
 * How to use: alert( singular_plural( '%d child', '%d children', 2 ) );
 *
 * @version 0.1
 * @date Monday, January 7, 2008
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 */
function singular_plural( strMsgSingular, strMsgPlural, intTotal ) {
	if ( intTotal > 1 )
		return strMsgPlural.replace( '%d', intTotal );
		return strMsgSingular.replace( '%d', intTotal );
}

Exemplos de uso:

alert( singular_plural( '%d child', '%d children', 2 ) );

alert( singular_plural( '%d child', '%d children', 1 ) );

Em ambos exemplos, teremos os seguinte resultados: 2 children e 1 child.

4 Comments

Joao  on February 8th, 2008

aert( singular_plural( ‘%d child’, ‘%d children’, 1 ) );

faltou o L

Leandro Vieira  on February 8th, 2008

Obrigado João.

Abraços.

Gabriel Sobrinho  on February 8th, 2008

Acabei de postar na função de php, é só converter e teremos essa também para JS.

Abraços

:)

Leandro Vieira  on February 11th, 2008

:D

Leave a Comment