2012-09-27 43 views
-2

有人請解釋使用在最後6號線中使用美元符號:美元說明在Javascript

function isAlphabet(elem) { 
    var alphaExp = /^[a-zA-Z]+$/; 

    if(elem.value.match(alphaExp)) 
     return true; 
    else 
     return false; 
} 
+3

該函數可以被冷凝以'返回elem.value.match(/^[A-Z] + $/I);'。 – Blender

+0

@Blender - 不喜歡GNU大括號的風格:「讓我們把大括號放在任何東西的中間」風格? (Ref:Your edit。) –

+1

@Blender實際上它是'return/^ [a-z] + $/i.test(elem.value)',因爲返回值應該是一個布爾值。 – xdazz

回答

1

這是一個正則表達式。 這意味着行的末尾。

這個正則表達式匹配是一個字符串,只有字母小寫和大寫。

  • ^表示線路
  • [a-zA-Z]字母大寫或小寫字符
  • +許多時間的開始的線
+0

它太逃避'.'表示任何字符,'\ .'表示字符「dot」 – 3on

1

在這方面的

  • $端,它錨定正則表達式模式到行尾。一個模式中的其他任何地方的$都只是一個$,但最後它是一個行尾錨點。

  • 2

    整個表達式,解釋

       |-------------- Match the start of the line 
           |   ----- Match the 'end of the line 
           |   | 
    var alphaExp = /^[a-zA-Z]+$/; 
           |------|| +-- Close the regular expression 
           | | || 
           | | |+---- Match one or more characters from the previous pattern 
           | | |----- Close the group 
           | |--------- Match characters between "a" and "z" and "A" and "Z" 
           |------------ Start a group 
    

    整個事情,在英文中的意思

    匹配任何以字符a-zA-Z和結束以相同字符的一個行開頭的行。

    0

    $匹配行結束。

    /^[a-zA-Z]+$/表示所有字符都是字母表。

    該功能還可以寫更乾淨,如:

    function isAlphabet(elem) { 
        return /^[a-z]+$/i.test(elem.value); 
    }