indexOf 用法

字號:


    indexOf用于發(fā)現一系列的字符在一個字符串中等位置并告訴你
    子字符串的起始位置。如果一個字符串中部包含該子字符串則
    indexOf返回returns "-1." 這里是一個例子:
    var the_word = "monkey";
    讓我們從單詞 "monkey"開始。
    var location_of_m = the_word.indexOf("m");
    location_of_m(字母m的位置)將為0,因為字母m位于該字符串
    的起始位置。var location_of_o = the_word.indexOf("o");
    location_of_o(字母o的位置)將為1。
    var location_of_key = the_word.indexOf("key");
    location_of_key(key的位置)將為3因為子字符串“key”以字母
    k開始,而k在單詞monkey中的位置是3。
    var location_of_y = the_word.indexOf("y");
    location_of_y)字母y的位置)是5。
    var cheeky = the_word.indexOf("q");
    cheeky值是-1,因為在單詞“monkey”中沒有字母q。
    indexOf更實用之處:
    var the_email = prompt("What's your email address?", "");
    var the_at_is_at = the_email.indexOf("@");
    if (the_at_is_at == -1)
    {
    alert("You loser, email addresses must
    have @ signs in them.");
    }
    這段代碼詢問用戶的電子郵件地址,如果用戶輸入的電子郵件
    地址中不包含字符 則 提示用戶"@你輸入的電子郵件地址
    無效,電子郵件的地址必須包含字符@。"
    charAt
    chatAt方法用于發(fā)現一個字符串中某個特定位置的字符。這里
    是一個例子:
    var the_word = "monkey";
    var the_first_letter = the_word.charAt(0);
    var the_second_letter = the_word.charAt(1);
    var the_last_letter = the_word.charAt(the_word.length-1);
    the_first_letter(第1個字符)是"m"
    the_second_letter(第2個字符)是"o"
    the_last_letter(最后一個字符)是 "y"
    注意利用字符串的length(長度)屬性你可以發(fā)現在包含多少個
    字符。在本例中,the_word是"monkey",所以the_word.length
    是6。不要忘記在一個字符串中第1個字符的位置是0,所以最后
    一個字符的位置就是length-1。所以在最后一行中用了
    the_word.length-1