12.7.删除或替换字符或单词

问题
我要删除字符串上的字符或替换它
解决办法
使用replace( )方法或split( )和join( )
讨论
ActionScript 3.0 提供一个新方法String.replace( ),用于字符替换,该方法接受两个参数:
pattern
查找或替换的字符串或正则表达式。
replace
替换的字符串,也可以是一个返回字符串的函数。

如果只提供一个参数时该方法有两个用途,这一节讨论字符串模式,正则表达式模式将在13.4节讨论。

这里有个简单的替换句子中的子串例子。replace( )方法返回替换掉的新字符串,原始字符串仍未被修改。
+展开
-ActionScript
var example:String = "This is a cool sentence."
//" is " 替换为" is not "
// 显示为:This is not a cool sentence.
trace( example.replace( " is "" is not " ) );

在这个例子中替换字符串为" is ",周围是有空格的,这点很重要,否则的话句子中的"This is"也会被替换为"This not is,",这就不是我们需要的结果了。

用字符串作为匹配模式有两个比较大的问题:替换次数和大小写问题,这些都要自己去处理,如通过循环来替换掉所有匹配子串:
+展开
-ActionScript
//创建字符串,一个原始的,一个为替换掉的
var example:String = "It's a bird, it's a plane, it's ActionScript Man!";
var replaced:String = example; // 先初始化为原始字符串
// 通过循环找出所有的"it's"子串,替换掉
while ( replaced.indexOf( "it's" ) != -1 ) {
// 替换"it's"为"it is".
replaced = replaced.replace( "it's""it is" );
}
// 解决大小写问题
replaced = replaced.replace( "It's""It is" );
// 最后输出为:It is a bird, it is a plane, it is ActionScript Man!
trace( replaced );

split( )方法也可以被用来替换或删除字符串中的字符或单词。不像replace( )方法把字符串作为匹配模式,split是替换所有的符号,但是这两个方法都是忽略大小写问题。下面的例子用\\n替换掉<br>:
+展开
-ActionScript
var example:String = "This is<br>a sentence<br>on 3 lines";
/* 显示:
This is
a sentence
on 3 lines
*/

trace( example.split( "<br>" ).join( '\n' ) );

split方法返回分离出的字符串数组,而Array.join( )方法把数组元素有重新组成一个新字符串Split方法删除了分隔符,而join( )方法正好相反,重新加入新的分隔符。

删除字符或单词就很简单了,只要替换为空串即可:
+展开
-ActionScript
var example:String = "This is a cool sentence.";
// 删除单词"cool"
// 显示:This is a sentence.
trace( example.replace( "cool """ ) );

加支付宝好友偷能量挖...


评论(0)网络
阅读(80)喜欢(0)flash/flex/fcs/AIR