我想执行这样的私人消息功能:
var a = "/pm John Hello John! this is a private message";
if(a.indexOf("/pm") >= 0){
//It contains the String!
trace("Contains /pm");
sendPM(toWho, Msg);
}
else{
sendPublicMsg();
}
检测字符串中是否有/pm
调用函数...
John
)Hello John! this is a private message
)。答案 0 :(得分:2)
其中一种方式:
var a = "/pm John Hello John! this is a private message";
var splitted:Array = a.split(" ");
if(splitted[0] == "/pm"){
sendPM(splitted[1], a.replace(splitted[0] + " " +splitted[1],""));
}
此处的优势超过indexOf
现在,如果您需要f.ex,现在可以在实际消息中使用/pm
。教约翰如何使用这个功能。
答案 1 :(得分:0)
解决此问题的另一种方法是使用正则表达式:
var a:String = "/pm John Hello John! this is a private message";
var privateMessagePattern:RegExp = /(\/pm) (\w+) (.*)/;
if(a.search(privateMessagePattern) == 0) {
var aMessage:Array = a.match(privateMessagePattern);
var recipient:String = aMessage[2];
var message:String = aMessage[3];
sendPM(recipient, message);
} else {
sendPublicMsg();
}
上面代码中的 aMessage 数组将包含4个元素(第一个是原始字符串,下一个元素是由 privateMessagePattern RegExp定义的3个组如果RegExp不匹配,则Array将为null,搜索方法返回的索引也为-1。