2010-04-18 47 views
1

我試圖在沒有循環的actionScript中執行首字母大寫,但是我被卡住了。我想選擇第一個字母或每個單詞,然後在該字母上應用大寫字母。那麼我的選擇部分是正確的,但是現在在一個死衚衕裏,有什麼想法?我試圖做到這一點沒有循環和切斷字符串。使用正則表達式在動作腳本中大寫每個單詞使用正則表達式大寫

// replaces with x since I can't figure out how to replace with 
// the found result as uppercase 
public function initialcaps():void 
{ 
    var pattern:RegExp=/\b[a-z]/g; 
    var myString:String="yes that is my dog dancing on the stage"; 
    var nuString:String=myString.replace(pattern,"x"); 
    trace(nuString); 
} 

回答

3

嘗試使用返回大寫字母的函數:

myString.replace(pattern, function($0){return $0.toUpperCase();}) 

此工程在JavaScript中至少。

+0

嗨濃湯,感謝您的答覆。這完美地工作,它只是爲匿名函數提供一個標誌(不是什麼大問題)。如果你不介意我問。 $ 0是多少? $似乎不在AS3文檔中。那麼這是如何工作的? – Deyon 2010-04-18 21:33:21

+0

@Deyon:'$ 0'只是一個常規變量標識符。你也可以使用'match'或任何你想要的。但由於'replace'使用'$ 1','$ 2'等來引用組匹配,'$ 0'是整個比賽的好名字。 – Gumbo 2010-04-18 21:53:04

4

您也可以使用它來避免編譯器警告。

myString.replace(pattern, function():String 
      { 
       return String(arguments[0]).toUpperCase(); 
      }); 
+0

謝謝。它幫助了很多。 :) – Ravish 2012-03-22 03:15:48

0

只是覺得應該把他們的兩分錢的字符串可以全部大寫

var pattern:RegExp = /\b[a-zA-Z]/g; 
myString = myString.toLowerCase().replace(pattern, function($0){return $0.toUpperCase();}); 
0

這個答案不拋出任何編譯器錯誤的下嚴格和我把它想更加健壯一些,處理像連字符這樣的邊緣情況(忽略它們),下劃線(將它們當作空格)以及其他特殊的非單詞字符(如斜槓或圓點)。

在正則表達式末尾註意/g開關非常重要。沒有它,函數的其餘部分是無用的,因爲它只會解決第一個單詞,而不是任何後續的單詞。

for each (var myText:String in ["this is your life", "Test-it", "this/that/the other thing", "welcome to the t.dot", "MC_special_button_04", "022s33FDs"]){ 
    var upperCaseEveryWord:String = myText.replace(/(\w)([-a-zA-Z0-9]*_?)/g, function(match:String, ... args):String { return args[0].toUpperCase() + args[1] }); 
    trace(upperCaseEveryWord); 
} 

輸出:

This Is Your Life 
Test-it 
This/That/The Other Thing 
Welcome To The T.Dot 
MC_Special_Button_04 
022s33FDs 

用於複製和粘貼的藝術家,這裏有一個現成的側傾功能:

public function upperCaseEveryWord(input:String):String { 
    return input.replace(/(\w)([-a-zA-Z0-9]*_?)/g, function(match:String, ... args):String { return args[0].toUpperCase() + args[1] }); 
}