Tip #1: Using negative numbers with String operationsTip #1: Usando números negativos con las operaciones de String

Every now and then you need to remove some characters from a String, and when is from the end of the String what I normally do is calculate the length of the String and subtract the amount of chars to remove.
for example:
1
2
var test:String = "This is a tip and trick";
trace (test.substr (18, test.length)); // Output: trick
But after checking the String Doc’s I found an alternative.
If endIndex is a negative number, the ending point is determined by counting back from the end of the string, where -1 is the last character.

So, with this we could do:

1
2
3
var test:String = "This is a tip and trick";
trace (test.slice(10, -10)); // Output: tip
trace (test.substr(-5)); // Output: trick

I don’t know if this is obvious for you but I haven’t tried this before…

Hope this can be useful
Gus

De vez en cuando tenemos que aplicar operaciones a cadena de caracteres (Strings) en las cuales debemos remover algunos de estos, y muchas veces estos se encuentran al final de la misma. En estos casos lo que normalmente haríamos sería calcular la longitud del mismo y tomar hasta ese punto.

Por ejemplo:
1
2
var test:String = "This is a tip and trick";
trace (test.substr (18, test.length)); // Output: trick
Revisando los docs de String dice:
If endIndex is a negative number, the ending point is determined by counting back from the end of the string, where -1 is the last character.
Lo que se traduce como:
Si el endIndex es un número negativo, el punto final es determinado contando desde el último caracter del String, tomando -1 como el último carácter.
Tomando esto en consideración podríamos obtener el mismo resultado del ejemplo anterior así:
1
2
3
var test:String = "This is a tip and trick";
trace (test.slice(10, -10)); // Output: tip
trace (test.substr(-5)); // Output: trick

No se si para ustedes esto sea obvio pero yo no lo había probado antes…

Espero que esto les sea de utilidad ;)
Gus

This entry was posted in Flex Tips & Tricks. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>