2010-04-22 16 views

Odpowiedz

27

Można używać RegExp.

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

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

do przycinania przód i tył strun, użyj

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

Jak mogę stworzyć własną RegExp. Czy są dostępne jakieś kawałki? – Benny

+0

@Benny Geo: Wypróbuj http://www.regular-expressions.info – Robusto

+4

Gwiazdka jest tutaj błędna, ponieważ gwiazdka również będzie pasować do ciągów o zerowej długości, a jeśli chcesz zastąpić wszystkie białe spacje jedną spacją, to nie będzie działać zgodnie z oczekiwaniami. Zamiast tego użyj znaku plusa - var rex: RegExp =/[\ s \ r \ n] +/gim; – Ofir

1

Najprostszym sposobem na usunięcie nie tylko przestrzeni, ale żadnej char dla tej sprawy, jest następujący,

//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

Jeśli masz dostęp do bibliotek AS3 Flex, jest też StringUtil.trim(" my string "). See here dla dokumentów.

Nie robi dokładnie tego, co OP był po, ale ponieważ była to najlepsza odpowiedź w google dla przycinania String AS3, pomyślałem, że warto byłoby opublikować to rozwiązanie dla bardziej zwykłego wymogu Stringy trimmy.

2

Przetestowane i działa na AnimateCC dla aplikacji iOS powietrza:

// 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); 
Powiązane problemy