2010-04-22 16 views

risposta

27

È possibile utilizzare RegExp.

var rex:RegExp = /[\s\r\n]+/gim; 
var str:String = "This is   a string."; 

str = str.replace(rex,''); 
// str is now "Thisisastring." 

Per rifilatura anteriore e posteriore delle stringhe, utilizzare

var rex:RegExp /^\s*|\s*$/gim; 
+0

Come posso creare la mia RegExp. C'è qualche tuts disponibile? – Benny

+0

@Benny Geo: prova http://www.regular-expressions.info – Robusto

+4

L'asterisco è sbagliato qui, poiché l'asterisco corrisponderà anche a stringhe di lunghezza zero e se vuoi sostituire tutti gli spazi bianchi con uno spazio non funzionerebbe come previsto. Utilizzare invece il segno più - var rex: RegExp =/[\ s \ r \ n] +/gim; – Ofir

1

Il modo più semplice di rimuovere non solo gli spazi ma qualsiasi char per quella materia, è la seguente,

//Tested on Flash CS5 and AIR 2.0 

//Regular expressions 
var spaces:RegExp =//gi; // match "spaces" in a string 
var dashes:RegExp = /-/gi; // match "dashes" in a string 

//Sample string with spaces and dashes 
var str:String = "Bu s ~ Tim e - 2-50-00"; 
str = str.replace(spaces, ""); // find and replace "spaces" 
str = str.replace(dashes, ":"); // find and replace "dashes" 

trace(str); // output: Bus~Time:2:50:00 
3

Se hai accesso alle librerie AS3 Flex, c'è anche StringUtil.trim(" my string "). See here per i documenti.

Non fa esattamente quello che l'OP era dopo, ma dato che questa era la risposta migliore su google per la trimming delle stringhe AS3, ho pensato che sarebbe valsa la pena postare questa soluzione per il più consueto requisito di Trimmy.

2

testato e funziona su AnimateCC per iOS aria app:

// Regular expressions 
var spaces:RegExp =//gi; // match "spaces" in a string 
var dashes:RegExp = /-/gi; // match "dashes" in a string 

// Sample string with spaces and dashes 
loginMC.userName.text = loginMC.userName.text.replace(spaces, ""); // find and replace "spaces" 
loginMC.userName.text = loginMC.userName.text.replace(dashes, ":"); // find and replace "dashes" 

trace(loginMC.userName.text); 
Problemi correlati