Publicado em 24.Jan.2008 por Filipe Sabella
Categorias: ActionScript
String.format() para ActionScript
Em diversas outras linguagens existe suporte para parsear Strings no formato “{0} aaa {1}”, substituindo os índices em chaves por valores passados para a função.
Precisei desta funcionalidade com um “algo a mais” em um projeto – suporte a pluralização. Não coloquei a função dentro de String.prototype para não bagunçar a cabeça de quem for manter meu código.
A função é simples:
1 2 3 | public static function format( text:String, values:Array ):String { return values == null || values.length == 0 ? "" : text.replace( new RegExp( "\\{(.*?)\\}", "gi" ), function():String{ return arguments[ 1 ].split( "," ).length == 1 ? values[ arguments[ 1 ] ] : arguments[ 1 ].split( "," )[ parseInt( values[ arguments[ 1 ].split( "," )[ 0 ] ] ) == 1 ? 1 : 2 ]; }); } |
Ou de uma forma mais legível:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package br.com.dclick.utils { public class StringUtils { private static const REGEXP:RegExp = new RegExp( "\\{(.*?)\\}", "gi" ); /** * Exemplo: * StringUtils.format( "{0}-{1} de {2} items", [ 1, 20, 1000 ] ) * retorna "1-20 de 1000 items". * * * A função também tem suporte simples a pluralização. Se um dos parametros ({x}) * se encontra no formato "{posicao com o valor a ser comparado, singular, plural}" * o parsing é realizado. * * Por exemplo, "{0}-{1} de {2} {2,item,items}". O último parâmetro indica que o * parâmetro 2 deve ser comparado. Se for igual a 1, a string "item" é retornada, * caso contrário, a string "items" é retornada. * Portanto, * StringUtils.format( "{0}-{1} de {2} {2,item,items}", [ 1, 20, 1000 ] ) * retorna "1-20 de 1000 items. Mas * StringUtils.format( "{0}-{1} de {2} {2,item,items}", [ 1, 1, 1 ] ) * retorna "1-1 de 1 item". * * @param text O fomato a ser usado * @param args Os valores para serem substituídos no formato. * @return A string formatada. * */ public static function format( text:String, values:Array ):String { if( values == null || values.length == 0 ) return text; return text.replace( REGEXP, function():String { // arguments: contem os groups capturados na RegExp. *Ver String.replace()* var split:Array = arguments[ 1 ].split( "," ); return split.length == 1 // {n} ? values[ arguments[ 1 ] ] // {n,s1,s2}, determina plural ou singular : split[ parseInt( values[ split[ 0 ] ] ) == 1 ? 1 : 2 ]; }); } } } |

Nenhum comentário
Deixe Seu Comentário