Flash / Flex / ActionScript/String/replace
Содержание
- 1 Remove characters or words instead of replacing them
- 2 Remove the tags and replace them with newline characters ("\n")
- 3 Removing and Replacing Characters and Words
- 4 replace(reCase, "\\$2, $1")
- 5 Replace with Regular Expression
- 6 Replacing
- 7 Use replace with while loop
- 8 Within the replacement string (the second parameter), you can use special values $1 to $9 to indicate the first nine remembered substrings
Remove characters or words instead of replacing them
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var example:String = "This is a cool sentence.";
trace( example.replace( "cool ", "" ) );
}
}
}
Remove the
tags and replace them with newline characters ("\n")
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var example:String = "This is<br>a sentence<br>on 3 lines";
trace( example.split( "<br>" ).join( "\n" ) );
}
}
}
Removing and Replacing Characters and Words
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var example:String = "This is a cool sentence."
trace( example.replace( " is ", " is not " ) );
}
}
}
replace(reCase, "\\$2, $1")
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var reCase:RegExp = new RegExp("(\\w+) (\\w+)", "gi");
var sVal = new String("ActionScript Bible");
var sRepl = sVal.replace(reCase, "\\$2, $1");
trace(sRepl);
}
}
}
Replace with Regular Expression
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var introduction:String = "My name is A!";
trace(introduction.replace(/my name is (\w+)/gi, "$1 is my name"));
}
}
}
Replacing
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var reCase:RegExp = new RegExp("shoot|crud|darn", "gi");
var sVal = new String("Shoot! More darn regular expression crud!");
var sRepl = sVal.replace(reCase, "%#@$");
trace(sRepl);
}
}
}
Use replace with while loop
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var example:String = "It"s a bird, it"s a plane, it"s ActionScript Man!";
var replaced:String = example; // Initialize replaced with the original text
while ( replaced.indexOf( "it"s" ) != -1 ) {
replaced = replaced.replace( "it"s", "it is" );
}
replaced = replaced.replace( "It"s", "It is" );
trace( replaced );
}
}
}
Within the replacement string (the second parameter), you can use special values $1 to $9 to indicate the first nine remembered substrings
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var reCase:RegExp = new RegExp("(\\w+) (\\w+)", "gi");
var sVal = new String("ActionScript Bible");
var sRepl = sVal.replace(reCase, "$2, $1");
trace(sRepl);
}
}
}