正則表達式

JS的正則表達式

//校驗是否全由數字組成
代碼

   1. function isDigit(s) 
   2. { 
   3. var patrn=/^[0-9]{1,20}$/; 
   4. if (!patrn.exec(s)) return false 
   5. return true 
   6. } 

//校驗登錄名:只能輸入5-20個以字母開頭、可帶數字、“_”、“.”的字串
代碼

   1. function isRegisterUserName(s) 
   2. { 
   3. var patrn=/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/; 
   4. if (!patrn.exec(s)) return false 
   5. return true 
   6. } 

//校驗用戶姓名:只能輸入1-30個以字母開頭的字串
代碼

   1. function isTrueName(s) 
   2. { 
   3. var patrn=/^[a-zA-Z]{1,30}$/; 
   4. if (!patrn.exec(s)) return false 
   5. return true 
   6. } 
   7. }} 
   8.  
   9. //校驗密碼:只能輸入6-20個字母、數字、下劃線 
  10. [code] 
  11. function isPasswd(s) 
  12. { 
  13. var patrn=/^(/w){6,20}$/; 
  14. if (!patrn.exec(s)) return false 
  15. return true 
  16. } 

//校驗普通電話、傳真號碼:可以“+”開頭,除數字外,可含有“-”
代碼

   1. function isTel(s) 
   2. { 
   3. //var patrn=/^[+]{0,1}(/d){1,3}[ ]?([-]?(/d){1,12})+$/; 
   4. var patrn=/^[+]{0,1}(/d){1,3}[ ]?([-]?((/d)|[ ]){1,12})+$/; 
   5. if (!patrn.exec(s)) return false 
   6. return true 
   7. } 

//校驗手機號碼:必須以數字開頭,除數字外,可含有“-”
代碼

   1. function isMobil(s) 
   2. { 
   3. var patrn=/^[+]{0,1}(/d){1,3}[ ]?([-]?((/d)|[ ]){1,12})+$/; 
   4. if (!patrn.exec(s)) return false 
   5. return true 
   6. } 

//校驗郵政編碼
代碼

   1. function isPostalCode(s) 
   2. { 
   3. //var patrn=/^[a-zA-Z0-9]{3,12}$/; 
   4. var patrn=/^[a-zA-Z0-9 ]{3,12}$/; 
   5. if (!patrn.exec(s)) return false 
   6. return true 
   7. } 

//校驗搜索關鍵字
代碼

   1. function isSearch(s) 
   2. { 
   3. var patrn=/^[^`~!@#$%^&*()+=|///][/]/{/}:;'/,.<>/?]{1}[^`~!@$%^&()+=|///] 
   4.         [/]/{/}:;'/,.<>?]{0,19}$/; 
   5. if (!patrn.exec(s)) return false 
   6. return true 
   7. } 
   8.  
   9. function isIP(s) //by zergling 
  10. { 
  11. var patrn=/^[0-9.]{1,20}$/; 
  12. if (!patrn.exec(s)) return false 
  13. return true 
  14. } 

正則表達式
代碼

   1. "^//d+$"  //非負整數(正整數 + 0) 
   2. "^[0-9]*[1-9][0-9]*$"  //正整數  
   3. "^((-//d+)|(0+))$"  //非正整數(負整數 + 0)  
   4. "^-[0-9]*[1-9][0-9]*$"  //負整數  
   5. "^-?//d+$"    //整數  
   6. "^//d+(//.//d+)?$"  //非負浮點數(正浮點數 + 0)  
   7. "^(([0-9]+//.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*//.[0-9]+)|([0-9]*[1-9][0-9]*))$"  
   8. //正浮點數  
   9. "^((-//d+(//.//d+)?)|(0+(//.0+)?))$"  //非正浮點數(負浮點數 + 0)  
  10. "^(-(([0-9]+//.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*//.[0-9]+)|([0-9]*[1-9][0-9]*)))$"  
  11. //負浮點數  
  12. "^(-?//d+)(//.//d+)?$"  //浮點數  
  13. "^[A-Za-z]+$"  //由26個英文字母組成的字符串  
  14. "^[A-Z]+$"  //由26個英文字母的大寫組成的字符串  
  15. "^[a-z]+$"  //由26個英文字母的小寫組成的字符串  
  16. "^[A-Za-z0-9]+$"  //由數字和26個英文字母組成的字符串  
  17. "^//w+$"  //由數字、26個英文字母或者下劃線組成的字符串  
  18. "^[//w-]+(//.[//w-]+)*@[//w-]+(//.[//w-]+)+$"    //email地址  
  19. "^[a-zA-z]+://(//w+(-//w+)*)(//.(//w+(-//w+)*))*(//?//S*)?$"  //url 
  20. "^[A-Za-z0-9_]*$"
 

正則表達式對象
本對象包含正則表達式模式以及表明如何應用模式的標誌。
代碼

   1. 語法 1 re = /pattern/[flags] 
   2. 語法 2 re = new RegExp("pattern",["flags"])  


參數
re
必選項。將要賦值爲正則表達式模式的變量名。

Pattern
必選項。要使用的正則表達式模式。如果使用語法 1,用 "/" 字符分隔模式。如果用語法 2,用引號將模式引起來。

Flags
可選項。如果使用語法 2 要用引號將 flag 引起來。標誌可以組合使用,可用的有:
代碼

   1. g (全文查找出現的所有 pattern)  
   2. i (忽略大小寫)  
   3. m (多行查找)  

示例
下面的示例創建一個包含正則表達式模式及相關標誌的對象(re),向您演示正則表達式對象的用法。在本例中,作爲結果的正則表達式對象又用於 match 方法中:
代碼

   1. function MatchDemo() 
   2. { 
   3. var r, re; // 聲明變量。 
   4. var s = "The rain in Spain falls mainly in the plain"; 
   5. re = new RegExp("ain","g"); // 創建正則表達式對象。 
   6. r = s.match(re); // 在字符串 s 中查找匹配。 
   7. return(r);  
   8. } 

返回值: ain,ain,ain,ain//
屬性 lastIndex 屬性 | source 屬性//
方法 compile 方法 | exec 方法 | test 方法//
要求 版本 3//
請參閱 RegExp 對象 | 正則表達式語法 | String 對象//

exec 方法
用正則表達式模式在字符串中運行查找,並返回包含該查找結果的一個數組。
rgExp.exec(str)

參數

rgExp
必選項。包含正則表達式模式和可用標誌的正則表達式對象。

str
必選項。要在其中執行查找的 String 對象或字符串文字。

說明//
如果 exec 方法沒有找到匹配,則它返回 null。如果它找到匹配,則 exec 方法返回一個數組,並且更新全局 RegExp 對象的屬性,以反映匹配結果。數組的0元素包含了完整的匹配,而第1到n元素中包含的是匹配中出現的任意一個子匹配。這相當於沒有設置全局標誌 (g) 的 match 方法。
如果爲正則表達式設置了全局標誌,exec 從以 lastIndex 的值指示的位置開始查找。如果沒有設置全局標誌,exec 忽略 lastIndex 的值,從字符串的起始位置開始搜索。

exec 方法返回的數組有三個屬性,分別是 input、index 和 lastIndex。Input 屬性包含了整個被查找的字符串。Index 屬性中包含了整個被查找字符串中被匹配的子字符串的位置。LastIndex 屬性中包含了匹配中最後一個字符的下一個位置。

示例//
下面的例子舉例說明了 exec 方法的用法:
代碼

   1. function RegExpTest() 
   2. { 
   3. var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion()) 
   4. if (ver >= 5.5){ // 測試 JScript 的版本。 
   5. var src = "The rain in Spain falls mainly in the plain."; 
   6. var re = //w+/g; // 創建正則表達式模式。 
   7. var arr; 
   8. while ((arr = re.exec(src)) != null) 
   9. document.write(arr.index + "-" + arr.lastIndex + arr + "/t"); 
  10. } 
  11. else{ 
  12. alert("請使用 JScript 的更新版本"); 
  13. } 
  14. } 

返回值:0-3The 4-8rain 9-11in 12-17Spain 18-23falls 24-30mainly 31-33in 34-37the 38-43plain

test 方法//
返回一個 Boolean 值,它指出在被查找的字符串中是否存在模式。
rgexp.test(str)

參數//
rgexp
必選項。包含正則表達式模式或可用標誌的正則表達式對象。

str
必選項。要在其上測試查找的字符串。

說明
test 方法檢查在字符串中是否存在一個模式,如果存在則返回 true,否則就返回 false。
全局 RegExp 對象的屬性不由 test 方法來修改。

示例
下面的例子舉例說明了 test 方法的用法:
代碼

   1. function TestDemo(re, s) 
   2. { 
   3. var s1; // 聲明變量。 
   4. // 檢查字符串是否存在正則表達式。 
   5. if (re.test(s)) // 測試是否存在。 
   6. s1 = " contains "; // s 包含模式。 
   7. else 
   8. s1 = " does not contain "; // s 不包含模式。 
   9. return("'" + s + "'" + s1 + "'"+ re.source + "'"); // 返回字符串。 
  10. } 

函數調用:document.write (TestDemo(/ain+/ ,"The rain in Spain falls mainly in the plain."));

返回值:'The rain in Spain falls mainly in the plain.' contains 'ain+'

match 方法
使用正則表達式模式對字符串執行查找,並將包含查找的結果作爲數組返回。//
stringObj.match(rgExp)

參數//
stringObj
必選項。對其進行查找的 String 對象或字符串文字。

rgExp
必選項。爲包含正則表達式模式和可用標誌的正則表達式對象。也可以是包含正則表達式模式和可用標誌的變量名或字符串文字。

說明//
如果 match 方法沒有找到匹配,返回 null。如果找到匹配返回一個數組並且更新全局 RegExp 對象的屬性以反映匹配結果。
match 方法返回的數組有三個屬性:input、index 和 lastIndex。Input 屬性包含整個的被查找字符串。Index 屬性包含了在整個被查找字符串中匹配的子字符串的位置。LastIndex 屬性包含了最後一次匹配中最後一個字符的下一個位置。
如果沒有設置全局標誌 (g),數組的 0 元素包含整個匹配,而第 1 到 n 元素包含了匹配中曾出現過的任一個子匹配。這相當於沒有設置全局標誌的 exec 方法。如果設置了全局標誌,元素 0 到 n 中包含所有匹配。

示例//
下面的示例演示了match 方法的用法:
代碼

   1. function MatchDemo() 
   2. { 
   3. var r, re; // 聲明變量。 
   4. var s = "The rain in Spain falls mainly in the plain"; 
   5. re = /ain/i; // 創建正則表達式模式。 
   6. r = s.match(re); // 嘗試匹配搜索字符串。 
   7. return(r); // 返回第一次出現 "ain" 的地方。 
   8. } 


返回值:ain

本示例說明帶 g 標誌設置的 match 方法的用法。
代碼

   1. function MatchDemo() 
   2. { 
   3. var r, re; // 聲明變量。 
   4. var s = "The rain in Spain falls mainly in the plain"; 
   5. re = /ain/ig; // 創建正則表達式模式。 
   6. r = s.match(re); // 嘗試去匹配搜索字符串。 
   7. return(r); // 返回的數組包含了所有 "ain"  
   8. // 出現的四個匹配。 
   9. } 


返回值:ain,ain,ain,ain

上面幾行代碼演示了字符串文字的 match 方法的用法。
代碼

   1. var r, re = "Spain"; 
   2. r = "The rain in Spain".replace(re, "Canada"); 
   3. return r; 


返回值:The rain in Canada

search 方法
返回與正則表達式查找內容匹配的第一個子字符串的位置。

stringObj.search(rgExp)

參數//
stringObj
必選項。要在其上進行查找的 String 對象或字符串文字。

rgExp
必選項。包含正則表達式模式和可用標誌的正則表達式對象。

說明

search 方法指明是否存在相應的匹配。如果找到一個匹配,search 方法將返回一個整數值,指明這個匹配距離字符串開始的偏移位置。如果沒有找到匹配,則返回 -1。

示例//
下面的示例演示了 search 方法的用法。
代碼

   1. function SearchDemo() 
   2. { 
   3. var r, re; // 聲明變量。 
   4. var s = "The rain in Spain falls mainly in the plain."; 
   5. re = /falls/i; // 創建正則表達式模式。 
   6. r = s.search(re); // 查找字符串。 
   7. return(r); // 返回 Boolean 結果。 

正則表達式語法
一個正則表達式就是由普通字符(例如字符 a 到 z)以及特殊字符(稱爲元字符)組成的文字模式。該模式描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作爲一個模板,將某個字符模式與所搜索的字符串進行匹配。

這裏有一些可能會遇到的正則表達式示例:
代碼

   1. JScript VBScript 匹配  
   2. /^/[ /t]*$/ "^/[ /t]*$" 匹配一個空白行。  
   3. //d{2}-/d{5}/ "/d{2}-/d{5}" 驗證一個ID 號碼是否由一個2位數字,一個連字符以及一個5位數字組成。  
   4. /<(.*)>.*<///1>/ "<(.*)>.*<///1>" 匹配一個 HTML 標記。  

下表是元字符及其在正則表達式上下文中的行爲的一個完整列表:

字符 描述
/ 將下一個字符標記爲一個特殊字符、或一個原義字符、或一個 後向引用、或一個八進制轉義符。例如,'n' 匹配字符 "n"。'/n' 匹配一個換行符。序列 '//' 匹配 "/" 而 "/(" 則匹配 "("。

^ 匹配輸入字符串的開始位置。如果設置了 RegExp 對象的 Multiline 屬性,^ 也匹配 '/n' 或 '/r' 之後的位置。

$ 匹配輸入字符串的結束位置。如果設置了RegExp 對象的 Multiline 屬性,$ 也匹配 '/n' 或 '/r' 之前的位置。

* 匹配前面的子表達式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"。 * 等價於{0,}。

+ 匹配前面的子表達式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等價於 {1,}。

? 匹配前面的子表達式零次或一次。例如,"do(es)?" 可以匹配 "do" 或 "does" 中的"do" 。? 等價於 {0,1}。

{n} n 是一個非負整數。匹配確定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的兩個 o。

{n,} n 是一個非負整數。至少匹配n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等價於 'o+'。'o{0,}' 則等價於 'o*'。

{n,m} m 和 n 均爲非負整數,其中n <= m。最少匹配 n 次且最多匹配 m 次。劉, "o{1,3}" 將匹配 "fooooood" 中的前三個 o。'o{0,1}' 等價於 'o?'。請注意在逗號和兩個數之間不能有空格。

? 當該字符緊跟在任何一個其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 後面時,匹配模式是非貪婪的。非貪婪模式儘可能少的匹配所搜索的字符串,而默認的貪婪模式則儘可能多的匹配所搜索的字符串。例如,對於字符串 "oooo",'o+?' 將匹配單個 "o",而 'o+' 將匹配所有 'o'。

. 匹配除 "/n" 之外的任何單個字符。要匹配包括 '/n' 在內的任何字符,請使用象 '[./n]' 的模式。
(pattern) 匹配pattern 並獲取這一匹配。所獲取的匹配可以從產生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中則使用 $0…$9 屬性。要匹配圓括號字符,請使用 '/(' 或 '/)'。

(?:pattern) 匹配 pattern 但不獲取匹配結果,也就是說這是一個非獲取匹配,不進行存儲供以後使用。這在使用 "或" 字符 (|) 來組合一個模式的各個部分是很有用。例如, 'industr(?:y|ies) 就是一個比 'industry|industries' 更簡略的表達式。

(?=pattern) 正向預查,在任何匹配 pattern 的字符串開始處匹配查找字符串。這是一個非獲取匹配,也就是說,該匹配不需要獲取供以後使用。例如, 'Windows (?=95|98|NT|2000)' 能匹配 "Windows 2000" 中的 "Windows" ,但不能匹配 "Windows 3.1" 中的 "Windows"。預查不消耗字符,也就是說,在一個匹配發生後,在最後一次匹配之後立即開始下一次匹配的搜索,而不是從包含預查的字符之後開始。

(?!pattern) 負向預查,在任何不匹配Negative lookahead matches the search string at any point where a string not matching pattern 的字符串開始處匹配查找字符串。這是一個非獲取匹配,也就是說,該匹配不需要獲取供以後使用。例如'Windows (?!95|98|NT|2000)' 能匹配 "Windows 3.1" 中的 "Windows",但不能匹配 "Windows 2000" 中的 "Windows"。預查不消耗字符,也就是說,在一個匹配發生後,在最後一次匹配之後立即開始下一次匹配的搜索,而不是從包含預查的字符之後開始

x|y 匹配 x 或 y。例如,'z|food' 能匹配 "z" 或 "food"。'(z|f)ood' 則匹配 "zood" 或 "food"。

[xyz] 字符集合。匹配所包含的任意一個字符。例如, '[abc]' 可以匹配 "plain" 中的 'a'。

[^xyz] 負值字符集合。匹配未包含的任意字符。例如, '[^abc]' 可以匹配 "plain" 中的'p'。

[a-z] 字符範圍。匹配指定範圍內的任意字符。例如,'[a-z]' 可以匹配 'a' 到 'z' 範圍內的任意小寫字母字符。

[^a-z] 負值字符範圍。匹配任何不在指定範圍內的任意字符。例如,'[^a-z]' 可以匹配任何不在 'a' 到 'z' 範圍內的任意字符。

/b 匹配一個單詞邊界,也就是指單詞和空格間的位置。例如, 'er/b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。

/B 匹配非單詞邊界。'er/B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。

/cx 匹配由x指明的控制字符。例如, /cM 匹配一個 Control-M 或回車符。 x 的值必須爲 A-Z 或 a-z 之一。否則,將 c 視爲一個原義的 'c' 字符。

/d 匹配一個數字字符。等價於 [0-9]。

/D 匹配一個非數字字符。等價於 [^0-9]。

/f 匹配一個換頁符。等價於 /x0c 和 /cL。

/n 匹配一個換行符。等價於 /x0a 和 /cJ。

/r 匹配一個回車符。等價於 /x0d 和 /cM。

/s 匹配任何空白字符,包括空格、製表符、換頁符等等。等價於 [ /f/n/r/t/v]。

/S 匹配任何非空白字符。等價於 [^ /f/n/r/t/v]。

/t 匹配一個製表符。等價於 /x09 和 /cI。

/v 匹配一個垂直製表符。等價於 /x0b 和 /cK。

/w 匹配包括下劃線的任何單詞字符。等價於'[A-Za-z0-9_]'。

/W 匹配任何非單詞字符。等價於 '[^A-Za-z0-9_]'。

/xn 匹配 n,其中 n 爲十六進制轉義值。十六進制轉義值必須爲確定的兩個數字長。例如, '/x41' 匹配 "A"。'/x041' 則等價於 '/x04' & "1"。正則表達式中可以使用 ASCII 編碼。.

/num 匹配 num,其中 num 是一個正整數。對所獲取的匹配的引用。例如,'(.)/1' 匹配兩個連續的相同字符。

/n 標識一個八進制轉義值或一個後向引用。如果 /n 之前至少 n 個獲取的子表達式,則 n 爲後向引用。否則,如果 n 爲八進制數字 (0-7),則 n 爲一個八進制轉義值。

/nm 標識一個八進制轉義值或一個後向引用。如果 /nm 之前至少有is preceded by at least nm 個獲取得子表達式,則 nm 爲後向引用。如果 /nm 之前至少有 n 個獲取,則 n 爲一個後跟文字 m 的後向引用。如果前面的條件都不滿足,若 n 和 m 均爲八進制數字 (0-7),則 /nm 將匹配八進制轉義值 nm。

/nml 如果 n 爲八進制數字 (0-3),且 m 和 l 均爲八進制數字 (0-7),則匹配八進制轉義值 nml。

/un 匹配 n,其中 n 是一個用四個十六進制數字表示的 Unicode 字符。例如, /u00A9 匹配版權符號 (?)。

優先權順序
在構造正則表達式之後,就可以象數學表達式一樣來求值,也就是說,可以從左至右並按照一個優先權順序來求值。

下表從最高優先級到最低優先級列出各種正則表達式操作符的優先權順序:
代碼

   1. 操作符 描述  
   2. / 轉義符  
   3. (), (?, (?=), [] 圓括號和方括號  
   4. *, +, ?, {n}, {n,}, {n,m} 限定符  
   5. ^, $, /anymetacharacter 位置和順序  
   6. | “或”操作  

普通字符

普通字符由所有那些未顯式指定爲元字符的打印和非打印字符組成。這包括所有的大寫和小寫字母字符,所有數字,所有標點符號以及一些符號。

最簡單的正則表達式是一個單獨的普通字符,可以匹配所搜索字符串中的該字符本身。例如,單字符模式 'A' 可以匹配所搜索字符串中任何位置出現的字母 'A'。這裏有一些單字符正則表達式模式的示例:
代碼

   1. /a/ 
   2. /7/ 
   3. /M/ 


等價的 VBScript 單字符正則表達式爲:
代碼

   1. "a" 
   2. "7" 
   3. "M" 


可以將多個單字符組合在一起得到一個較大的表達式。例如,下面的 JScript 正則表達式不是別的,就是通過組合單字符表達式 'a'、'7'以及 'M' 所創建出來的一個表達式。

/a7M/
等價的 VBScript 表達式爲:

"a7M"
請注意這裏沒有連接操作符。所需要做的就是將一個字符放在了另一個字符後面。

正則表達式語法
一個正則表達式就是由普通字符(例如字符 a 到 z)以及特殊字符(稱爲元字符)組成的文字模式。該模式描述在查找文字主體時待匹配的一個或多個字符串。正則表達式作爲一個模板,將某個字符模式與所搜索的字符串進行匹配。

這裏有一些可能會遇到的正則表達式示例:
代碼

   1. JScript VBScript 匹配  
   2. /^/[ /t]*$/ "^/[ /t]*$" 匹配一個空白行。  
   3. //d{2}-/d{5}/ "/d{2}-/d{5}" 驗證一個ID 號碼是否由一個2位數字,一個連字符以及一個5位數字組成。  
   4. /<(.*)>.*<///1>/ "<(.*)>.*<///1>" 匹配一個 HTML 標記。  

下表是元字符及其在正則表達式上下文中的行爲的一個完整列表:

字符 描述
/ 將下一個字符標記爲一個特殊字符、或一個原義字符、或一個 後向引用、或一個八進制轉義符。例如,'n' 匹配字符 "n"。'/n' 匹配一個換行符。序列 '//' 匹配 "/" 而 "/(" 則匹配 "("。

^ 匹配輸入字符串的開始位置。如果設置了 RegExp 對象的 Multiline 屬性,^ 也匹配 '/n' 或 '/r' 之後的位置。

$ 匹配輸入字符串的結束位置。如果設置了RegExp 對象的 Multiline 屬性,$ 也匹配 '/n' 或 '/r' 之前的位置。

* 匹配前面的子表達式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"。 * 等價於{0,}。

+ 匹配前面的子表達式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等價於 {1,}。

? 匹配前面的子表達式零次或一次。例如,"do(es)?" 可以匹配 "do" 或 "does" 中的"do" 。? 等價於 {0,1}。

{n} n 是一個非負整數。匹配確定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的兩個 o。

{n,} n 是一個非負整數。至少匹配n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等價於 'o+'。'o{0,}' 則等價於 'o*'。

{n,m} m 和 n 均爲非負整數,其中n <= m。最少匹配 n 次且最多匹配 m 次。劉, "o{1,3}" 將匹配 "fooooood" 中的前三個 o。'o{0,1}' 等價於 'o?'。請注意在逗號和兩個數之間不能有空格。

? 當該字符緊跟在任何一個其他限制符 (*, +, ?, {n}, {n,}, {n,m}) 後面時,匹配模式是非貪婪的。非貪婪模式儘可能少的匹配所搜索的字符串,而默認的貪婪模式則儘可能多的匹配所搜索的字符串。例如,對於字符串 "oooo",'o+?' 將匹配單個 "o",而 'o+' 將匹配所有 'o'。

. 匹配除 "/n" 之外的任何單個字符。要匹配包括 '/n' 在內的任何字符,請使用象 '[./n]' 的模式。
(pattern) 匹配pattern 並獲取這一匹配。所獲取的匹配可以從產生的 Matches 集合得到,在VBScript 中使用 SubMatches 集合,在JScript 中則使用 $0…$9 屬性。要匹配圓括號字符,請使用 '/(' 或 '/)'。

(?:pattern) 匹配 pattern 但不獲取匹配結果,也就是說這是一個非獲取匹配,不進行存儲供以後使用。這在使用 "或" 字符 (|) 來組合一個模式的各個部分是很有用。例如, 'industr(?:y|ies) 就是一個比 'industry|industries' 更簡略的表達式。

(?=pattern) 正向預查,在任何匹配 pattern 的字符串開始處匹配查找字符串。這是一個非獲取匹配,也就是說,該匹配不需要獲取供以後使用。例如, 'Windows (?=95|98|NT|2000)' 能匹配 "Windows 2000" 中的 "Windows" ,但不能匹配 "Windows 3.1" 中的 "Windows"。預查不消耗字符,也就是說,在一個匹配發生後,在最後一次匹配之後立即開始下一次匹配的搜索,而不是從包含預查的字符之後開始。

(?!pattern) 負向預查,在任何不匹配Negative lookahead matches the search string at any point where a string not matching pattern 的字符串開始處匹配查找字符串。這是一個非獲取匹配,也就是說,該匹配不需要獲取供以後使用。例如'Windows (?!95|98|NT|2000)' 能匹配 "Windows 3.1" 中的 "Windows",但不能匹配 "Windows 2000" 中的 "Windows"。預查不消耗字符,也就是說,在一個匹配發生後,在最後一次匹配之後立即開始下一次匹配的搜索,而不是從包含預查的字符之後開始

x|y 匹配 x 或 y。例如,'z|food' 能匹配 "z" 或 "food"。'(z|f)ood' 則匹配 "zood" 或 "food"。

[xyz] 字符集合。匹配所包含的任意一個字符。例如, '[abc]' 可以匹配 "plain" 中的 'a'。

[^xyz] 負值字符集合。匹配未包含的任意字符。例如, '[^abc]' 可以匹配 "plain" 中的'p'。

[a-z] 字符範圍。匹配指定範圍內的任意字符。例如,'[a-z]' 可以匹配 'a' 到 'z' 範圍內的任意小寫字母字符。

[^a-z] 負值字符範圍。匹配任何不在指定範圍內的任意字符。例如,'[^a-z]' 可以匹配任何不在 'a' 到 'z' 範圍內的任意字符。

/b 匹配一個單詞邊界,也就是指單詞和空格間的位置。例如, 'er/b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。

/B 匹配非單詞邊界。'er/B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。

/cx 匹配由x指明的控制字符。例如, /cM 匹配一個 Control-M 或回車符。 x 的值必須爲 A-Z 或 a-z 之一。否則,將 c 視爲一個原義的 'c' 字符。

/d 匹配一個數字字符。等價於 [0-9]。

/D 匹配一個非數字字符。等價於 [^0-9]。

/f 匹配一個換頁符。等價於 /x0c 和 /cL。

/n 匹配一個換行符。等價於 /x0a 和 /cJ。

/r 匹配一個回車符。等價於 /x0d 和 /cM。

/s 匹配任何空白字符,包括空格、製表符、換頁符等等。等價於 [ /f/n/r/t/v]。

/S 匹配任何非空白字符。等價於 [^ /f/n/r/t/v]。

/t 匹配一個製表符。等價於 /x09 和 /cI。

/v 匹配一個垂直製表符。等價於 /x0b 和 /cK。

/w 匹配包括下劃線的任何單詞字符。等價於'[A-Za-z0-9_]'。

/W 匹配任何非單詞字符。等價於 '[^A-Za-z0-9_]'。

/xn 匹配 n,其中 n 爲十六進制轉義值。十六進制轉義值必須爲確定的兩個數字長。例如, '/x41' 匹配 "A"。'/x041' 則等價於 '/x04' & "1"。正則表達式中可以使用 ASCII 編碼。.

/num 匹配 num,其中 num 是一個正整數。對所獲取的匹配的引用。例如,'(.)/1' 匹配兩個連續的相同字符。

/n 標識一個八進制轉義值或一個後向引用。如果 /n 之前至少 n 個獲取的子表達式,則 n 爲後向引用。否則,如果 n 爲八進制數字 (0-7),則 n 爲一個八進制轉義值。

/nm 標識一個八進制轉義值或一個後向引用。如果 /nm 之前至少有is preceded by at least nm 個獲取得子表達式,則 nm 爲後向引用。如果 /nm 之前至少有 n 個獲取,則 n 爲一個後跟文字 m 的後向引用。如果前面的條件都不滿足,若 n 和 m 均爲八進制數字 (0-7),則 /nm 將匹配八進制轉義值 nm。

/nml 如果 n 爲八進制數字 (0-3),且 m 和 l 均爲八進制數字 (0-7),則匹配八進制轉義值 nml。

/un 匹配 n,其中 n 是一個用四個十六進制數字表示的 Unicode 字符。例如, /u00A9 匹配版權符號 (?)。

優先權順序
在構造正則表達式之後,就可以象數學表達式一樣來求值,也就是說,可以從左至右並按照一個優先權順序來求值。

下表從最高優先級到最低優先級列出各種正則表達式操作符的優先權順序:
代碼

   1. 操作符 描述  
   2. / 轉義符  
   3. (), (?, (?=), [] 圓括號和方括號  
   4. *, +, ?, {n}, {n,}, {n,m} 限定符  
   5. ^, $, /anymetacharacter 位置和順序  
   6. | “或”操作  

普通字符

普通字符由所有那些未顯式指定爲元字符的打印和非打印字符組成。這包括所有的大寫和小寫字母字符,所有數字,所有標點符號以及一些符號。

最簡單的正則表達式是一個單獨的普通字符,可以匹配所搜索字符串中的該字符本身。例如,單字符模式 'A' 可以匹配所搜索字符串中任何位置出現的字母 'A'。這裏有一些單字符正則表達式模式的示例:
代碼

   1. /a/ 
   2. /7/ 
   3. /M/ 


等價的 VBScript 單字符正則表達式爲:
代碼

   1. "a" 
   2. "7" 
   3. "M" 


可以將多個單字符組合在一起得到一個較大的表達式。例如,下面的 JScript 正則表達式不是別的,就是通過組合單字符表達式 'a'、'7'以及 'M' 所創建出來的一個表達式。

/a7M/
等價的 VBScript 表達式爲:

"a7M"
請注意這裏沒有連接操作符。所需要做的就是將一個字符放在了另一個字符後面。


正則表達式使用詳解
簡介

簡單的說,正則表達式是一種可以用於模式匹配和替換的強有力的工具。其作用如下:
測試字符串的某個模式。例如,可以對一個輸入字符串進行測試,看在該字符串是否存在一個電話號碼模式或一個信用卡號碼模式。這稱爲數據有效性驗證。
替換文本。可以在文檔中使用一個正則表達式來標識特定文字,然後可以全部將其刪除,或者替換爲別的文字。
根據模式匹配從字符串中提取一個子字符串。可以用來在文本或輸入字段中查找特定文字。

基本語法

在對正則表達式的功能和作用有了初步的瞭解之後,我們就來具體看一下正則表達式的語法格式。
正則表達式的形式一般如下:  

/love/  其中位於“/”定界符之間的部分就是將要在目標對象中進行匹配的模式。用戶只要把希望查找匹配對象的模式內容放入“/”定界符之間即可。爲了能夠使用戶更加靈活的定製模式內容,正則表達式提供了專門的“元字符”。所謂元字符就是指那些在正則表達式中具有特殊意義的專用字符,可以用來規定其前導字符(即位於元字符前面的字符)在目標對象中的出現模式。
較爲常用的元字符包括: “+”, “*”,以及 “?”。

“+”元字符規定其前導字符必須在目標對象中連續出現一次或多次。

“*”元字符規定其前導字符必須在目標對象中出現零次或連續多次。

“?”元字符規定其前導對象必須在目標對象中連續出現零次或一次。

下面,就讓我們來看一下正則表達式元字符的具體應用。

/fo+/  因爲上述正則表達式中包含“+”元字符,表示可以與目標對象中的 “fool”, “fo”, 或者 “football”等在字母f後面連續出現一個或多個字母o的字符串相匹配。

/eg*/  因爲上述正則表達式中包含“*”元字符,表示可以與目標對象中的 “easy”, “ego”, 或者 “egg”等在字母e後面連續出現零個或多個字母g的字符串相匹配。

/Wil?/  因爲上述正則表達式中包含“?”元字符,表示可以與目標對象中的 “Win”, 或者“Wilson”,等在字母i後面連續出現零個或一個字母l的字符串相匹配。

有時候不知道要匹配多少字符。爲了能適應這種不確定性,正則表達式支持限定符的概念。這些限定符可以指定正則表達式的一個給定組件必須要出現多少次才能滿足匹配。

{n} n 是一個非負整數。匹配確定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的兩個 o。

{n,} n 是一個非負整數。至少匹配 n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等價於 'o+'。'o{0,}' 則等價於 'o*'。

{n,m} m 和 n 均爲非負整數,其中n <= m。最少匹配 n 次且最多匹配 m 次。例如,"o{1,3}" 將匹配 "fooooood" 中的前三個 o。'o{0,1}' 等價於 'o?'。請注意在逗號和兩個數之間不能有空格。

除了元字符之外,用戶還可以精確指定模式在匹配對象中出現的頻率。例如,/jim {2,6}/ 上述正則表達式規定字符m可以在匹配對象中連續出現2-6次,因此,上述正則表達式可以同jimmy或jimmmmmy等字符串相匹配。
在對如何使用正則表達式有了初步瞭解之後,我們來看一下其它幾個重要的元字符的使用方式。
代碼

   1. /s:用於匹配單個空格符,包括tab鍵和換行符;  
   2. /S:用於匹配除單個空格符之外的所有字符;  
   3. /d:用於匹配從0到9的數字;  
   4. /w:用於匹配字母,數字或下劃線字符;  
   5. /W:用於匹配所有與/w不匹配的字符;  
   6. . :用於匹配除換行符之外的所有字符。  


(說明:我們可以把/s和/S以及/w和/W看作互爲逆運算)
下面,我們就通過實例看一下如何在正則表達式中使用上述元字符。
//s+/ 上述正則表達式可以用於匹配目標對象中的一個或多個空格字符。
//d000/ 如果我們手中有一份複雜的財務報表,那麼我們可以通過上述正則表達式輕而易舉的查找到所有總額達千元的款項。
除了我們以上所介紹的元字符之外,正則表達式中還具有另外一種較爲獨特的專用字符,即定位符。定位符用於規定匹配模式在目標對象中的出現位置。 較爲常用的定位符包括: “^”, “$”, “/b” 以及 “/B”。
代碼

   1. “^”定位符規定匹配模式必須出現在目標字符串的開頭 
   2. “$”定位符規定匹配模式必須出現在目標對象的結尾 
   3. “/b”定位符規定匹配模式必須出現在目標字符串的開頭或結尾的兩個邊界之一 
   4. “/B”定位符則規定匹配對象必須位於目標字符串的開頭和結尾兩個邊界之內, 
   5.       即匹配對象既不能作爲目標字符串的開頭,也不能作爲目標字符串的結尾。 


同樣,我們也可以把“^”和“$”以及“/b”和“/B”看作是互爲逆運算的兩組定位符。舉例來說: /^hell/ 因爲上述正則表達式中包含“^”定位符,所以可以與目標對象中以 “hell”, “hello”或“hellhound”開頭的字符串相匹配。 /ar$/ 因爲上述正則表達式中包含“$”定位符,所以可以與目標對象中以 “car”, “bar”或 “ar” 結尾的字符串相匹配。 //bbom/ 因爲上述正則表達式模式以“/b”定位符開頭,所以可以與目標對象中以 “bomb”, 或 “bom”開頭的字符串相匹配。/man/b/ 因爲上述正則表達式模式以“/b”定位符結尾,所以可以與目標對象中以 “human”, “woman”或 “man”結尾的字符串相匹配。
爲了能夠方便用戶更加靈活的設定匹配模式,正則表達式允許使用者在匹配模式中指定某一個範圍而不侷限於具體的字符。例如:
代碼

   1. /[A-Z]/  上述正則表達式將會與從A到Z範圍內任何一個大寫字母相匹配。 
   2. /[a-z]/  上述正則表達式將會與從a到z範圍內任何一個小寫字母相匹配。  
   3. /[0-9]/  上述正則表達式將會與從0到9範圍內任何一個數字相匹配。  
   4. /([a-z][A-Z][0-9])+/ 上述正則表達式將會與任何由字母和數字組成的字符串,如 “aB0” 等相匹配。 


這裏需要提醒用戶注意的一點就是可以在正則表達式中使用 “()” 把字符串組合在一起。“()”符號包含的內容必須同時出現在目標對象中。因此,上述正則表達式將無法與諸如 “abc”等的字符串匹配,因爲“abc”中的最後一個字符爲字母而非數字。
如果我們希望在正則表達式中實現類似編程邏輯中的“或”運算,在多個不同的模式中任選一個進行匹配的話,可以使用管道符 “|”。例如:/to|too|2/ 上述正則表達式將會與目標對象中的 “to”, “too”, 或 “2” 相匹配。
正則表達式中還有一個較爲常用的運算符,即否定符 “[^]”。與我們前文所介紹的定位符 “^” 不同,否定符 “[^]”規定目標對象中不能存在模式中所規定的字符串。例如:/[^A-C]/ 上述字符串將會與目標對象中除A,B,和C之外的任何字符相匹配。一般來說,當“^”出現在 “[]”內時就被視做否定運算符;而當“^”位於“[]”之外,或沒有“[]”時,則應當被視做定位符。
最後,當用戶需要在正則表達式的模式中加入元字符,並查找其匹配對象時,可以使用轉義符“/”。例如:/Th/*/  上述正則表達式將會與目標對象中的“Th*”而非“The”等相匹配。
在構造正則表達式之後,就可以象數學表達式一樣來求值,也就是說,可以從左至右並按照一個優先級順序來求值。優先級如下:
代碼

   1. 1./ 轉義符 
   2. 2.(), (?, (?=), [] 圓括號和方括號 
   3. 3.*, +, ?, {n}, {n,}, {n,m} 限定符 
   4. 4.^, $, /anymetacharacter 位置和順序 
   5. 5.|“或”操作 

使用實例
在JavaScript 1.2中帶有一個功能強大的RegExp()對象,可以用來進行正則表達式的匹配操作。其中的test()方法可以檢驗目標對象中是否包含匹配模式,並相應的返回true或false。
我們可以使用JavaScript編寫以下腳本,驗證用戶輸入的郵件地址的有效性。
代碼

   1. <html>  
   2. <head>  
   3.   <script language="Javascript1.2">  
   4.      <!-- start hiding  
   5.      function verifyAddress(obj)  
   6.      {  
   7.       var email = obj.email.value;  
   8.       var pattern =  
   9. /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(/.[a-zA-Z0-9_-])+/;  
  10.       flag = pattern.test(email);  
  11.       if(flag)  
  12.       {  
  13.        alert(“Your email address is correct!”);  
  14.        return true;  
  15.       }  
  16.       else  
  17.        {  
  18.         alert(“Please try again!”);  
  19.         return false;  
  20.         }  
  21.       }  
  22.      // stop hiding -->  
  23.     </script>  
  24.   </head>  
  25.   <body>  
  26.    <form onSubmit="return verifyAddress(this);">  
  27.     <input name="email" type="text">  
  28.     <input type="submit">  
  29.     </form>  
  30.   </body>  
  31. </html>

 

這篇介紹javascript方面的日誌,我在是Clang上看到的。作者介紹挺全面的,所以轉載過來讓感興趣的朋友看一下。呵呵~~~

有些時候你精通一門語言,但是會發現你其實整天在和其它語言打交道,也許你以爲這些微不足道,不至於影響你的開發進度,但恰恰是這些你不重視的東西會浪費你很多時間,我一直以爲我早在幾年前就已經精通JavaScript了,直到目前,我才越來越覺得JavaScript遠比我想象的複雜和強大,我開始崇拜它,
趁着節日的空隙,把有關JavaScript的方法和技巧整理下,讓每個在爲JavaScript而煩惱的人明白,JavaScript就這麼回事!並希望JavaScript還可以成爲你的朋友,讓你豁然開朗,在項目中更好的應用~

適合閱讀範圍:對JavaScript一無所知~離精通只差一步之遙的人
基礎知識:HTML


JavaScript就這麼回事1:基礎知識

1 創建腳本塊

1: <script language=”JavaScript”>
2: JavaScript code goes here
3: </script>

 

2 隱藏腳本代碼

1: <script language=”JavaScript”>
2: <!--
3: document.write(“Hello”);
4: // -->
5: </script>


在不支持JavaScript的瀏覽器中將不執行相關代碼

3 瀏覽器不支持的時候顯示

1: <noscript>
2: Hello to the non-JavaScript browser.
3: </noscript>

 

4 鏈接外部腳本文件

1: <script language=”JavaScript” src="/”filename.js"”></script>


5 註釋腳本

1: // This is a comment
2: document.write(“Hello”); // This is a comment
3: /*
4: All of this
5: is a comment
6: */

 

6 輸出到瀏覽器

1: document.write(“<strong>Hello</strong>”);

 

7 定義變量

1: var myVariable = “some value”;

 

8 字符串相加

1: var myString = “String1” + “String2”;

 

9 字符串搜索

1: <script language=”JavaScript”>
2: <!--
3: var myVariable = “Hello there”;
4: var therePlace = myVariable.search(“there”);
5: document.write(therePlace);
6: // -->
7: </script>

 

10 字符串替換

1: thisVar.replace(“Monday”,”Friday”);


11 格式化字串

1: <script language=”JavaScript”>
2: <!--
3: var myVariable = “Hello there”;
4: document.write(myVariable.big() + “<br/>”);
5: document.write(myVariable.blink() + “<br/>”);
6: document.write(myVariable.bold() + “<br/>”);
7: document.write(myVariable.fixed() + “<br/>”);
8: document.write(myVariable.fontcolor(“red”) + “<br/>”);
9: document.write(myVariable.fontsize(“18pt”) + “<br/>”);
10: document.write(myVariable.italics() + “<br/>”);
11: document.write(myVariable.small() + “<br/>”);
12: document.write(myVariable.strike() + “<br/>”);
13: document.write(myVariable.sub() + “<br/>”);
14: document.write(myVariable.sup() + “<br/>”);
15: document.write(myVariable.toLowerCase() + “<br/>”);
16: document.write(myVariable.toUpperCase() + “<br/>”);
17:
18: var firstString = “My String”;
19: var finalString = firstString.bold().toLowerCase().fontcolor(“red”);
20: // -->
21: </script>

 

12 創建數組

1: <script language=”JavaScript”>
2: <!--
3: var myArray = new Array(5);
4: myArray[0] = “First Entry”;
5: myArray[1] = “Second Entry”;
6: myArray[2] = “Third Entry”;
7: myArray[3] = “Fourth Entry”;
8: myArray[4] = “Fifth Entry”;
9: var anotherArray = new Array(“First Entry”,”Second Entry”,”Third Entry”,”Fourth Entry”,”Fifth Entry”);
10: // -->
11: </script>

 

13 數組排序

1: <script language=”JavaScript”>
2: <!--
3: var myArray = new Array(5);
4: myArray[0] = “z”;
5: myArray[1] = “c”;
6: myArray[2] = “d”;
7: myArray[3] = “a”;
8: myArray[4] = “q”;
9: document.write(myArray.sort());
10: // -->
11: </script>

 

14 分割字符串

1: <script language=”JavaScript”>
2: <!--
3: var myVariable = “a,b,c,d”;
4: var stringArray = myVariable.split(“,”);
5: document.write(stringArray[0]);
6: document.write(stringArray[1]);
7: document.write(stringArray[2]);
8: document.write(stringArray[3]);
9: // -->
10: </script>

 

15 彈出警告信息

1: <script language=”JavaScript”>
2: <!--
3: window.alert(“Hello”);
4: // -->
5: </script>

 

16 彈出確認框

1: <script language=”JavaScript”>
2: <!--
3: var result = window.confirm(“Click OK to continue”);
4: // -->
5: </script>

 

17 定義函數

1: <script language=”JavaScript”>
2: <!--
3: function multiple(number1,number2) {
4: var result = number1 * number2;
5: return result;
6: }
7: // -->
8: </script>

 

18 調用JS函數

1: <a href=”#” onClick=”functionName()”>Link text</a>
2: <a href="/”javascript:functionName"()”>Link text</a>

 

19 在頁面加載完成後執行函數

1: <body onLoad=”functionName();”>
2: Body of the page
3: </body>


20 條件判斷

1: <script>
2: <!--
3: var userChoice = window.confirm(“Choose OK or Cancel”);
4: var result = (userChoice == true) ? “OK” : “Cancel”;
5: document.write(result);
6: // -->
7: </script>

 

21 指定次數循環

1: <script>
2: <!--
3: var myArray = new Array(3);
4: myArray[0] = “Item 0”;
5: myArray[1] = “Item 1”;
6: myArray[2] = “Item 2”;
7: for (i = 0; i < myArray.length; i++) {
8: document.write(myArray[i] + “<br/>”);
9: }
10: // -->
11: </script>

 

22 設定將來執行

1: <script>
2: <!--
3: function hello() {
4: window.alert(“Hello”);
5: }
6: window.setTimeout(“hello()”,5000);
7: // -->
8: </script>

 

23 定時執行函數

1: <script>
2: <!--
3: function hello() {
4: window.alert(“Hello”);
5: window.setTimeout(“hello()”,5000);
6: }
7: window.setTimeout(“hello()”,5000);
8: // -->
9: </script>

 

24 取消定時執行

1: <script>
2: <!--
3: function hello() {
4: window.alert(“Hello”);
5: }
6: var myTimeout = window.setTimeout(“hello()”,5000);
7: window.clearTimeout(myTimeout);
8: // -->
9: </script>

 

25 在頁面卸載時候執行函數

1: <body onUnload=”functionName();”>
2: Body of the page
3: </body>

JavaScript就這麼回事2:瀏覽器輸出


26 訪問document對象

1: <script language=”JavaScript”>
2: var myURL = document.URL;
3: window.alert(myURL);
4: </script>

 

27 動態輸出HTML

1: <script language=”JavaScript”>
2: document.write(“<p>Here’s some information about this document:</p>”);
3: document.write(“<ul>”);
4: document.write(“<li>Referring Document: “ + document.referrer + “</li>”);
5: document.write(“<li>Domain: “ + document.domain + “</li>”);
6: document.write(“<li>URL: “ + document.URL + “</li>”);
7: document.write(“</ul>”);
8: </script>


28 輸出換行

1: document.writeln(“<strong>a</strong>”);
2: document.writeln(“b”);

 

29 輸出日期

1: <script language=”JavaScript”>
2: var thisDate = new Date();
3: document.write(thisDate.toString());
4: </script>

 

30 指定日期的時區

1: <script language=”JavaScript”>
2: var myOffset = -2;
3: var currentDate = new Date();
4: var userOffset = currentDate.getTimezoneOffset()/60;
5: var timeZoneDifference = userOffset - myOffset;
6: currentDate.setHours(currentDate.getHours() + timeZoneDifference);
7: document.write(“The time and date in Central Europe is: “ + currentDate.toLocaleString());
8: </script>


31 設置日期輸出格式

1: <script language=”JavaScript”>
2: var thisDate = new Date();
3: var thisTimeString = thisDate.getHours() + “:” + thisDate.getMinutes();
4: var thisDateString = thisDate.getFullYear() + “/” + thisDate.getMonth() + “/” + thisDate.getDate();
5: document.write(thisTimeString + “ on “ + thisDateString);
6: </script>


32 讀取URL參數

1: <script language=”JavaScript”>
2: var urlParts = document.URL.split(“?”);
3: var parameterParts = urlParts[1].split(“&”);
4: for (i = 0; i < parameterParts.length; i++) {
5: var pairParts = parameterParts[i].split(“=”);
6: var pairName = pairParts[0];
7: var pairValue = pairParts[1];
8: document.write(pairName + “ :“ +pairValue );
9: }
10: </script>

你還以爲HTML是無狀態的麼?

33 打開一個新的document對象

1: <script language=”JavaScript”>
2: function newDocument() {
3: document.open();
4: document.write(“<p>This is a New Document.</p>”);
5: document.close();
6: }
7: </script>

 

34 頁面跳轉

1: <script language=”JavaScript”>
2: window.location = “http://www.liu21st.com/”;
3: </script>

 

35 添加網頁加載進度窗口

1: <html>
2: <head>
3: <script language='javaScript'>
4: var placeHolder = window.open('holder.html','placeholder','width=200,height=200');
5: </script>
6: <title>The Main Page</title>
7: </head>
8: <body onLoad='placeHolder.close()'>
9: <p>This is the main page</p>
10: </body>
11: </html>

36 讀取圖像屬性

1: <img src="/”image1.jpg"” name=”myImage”>
2: <a href=”# ” onClick=”window.alert(document.myImage.width)”>Width</a>
3:


37 動態加載圖像

1: <script language=”JavaScript”>
2: myImage = new Image;
3: myImage.src = “Tellers1.jpg”;
4: </script>


38 簡單的圖像替換

1: <script language=”JavaScript”>
2: rollImage = new Image;
3: rollImage.src = “rollImage1.jpg”;
4: defaultImage = new Image;
5: defaultImage.src = “image1.jpg”;
6: </script>
7: <a href="/”myUrl"” onMouseOver=”document.myImage.src = rollImage.src;”
8: onMouseOut=”document.myImage.src = defaultImage.src;”>
9: <img src="/”image1.jpg"” name=”myImage” width=100 height=100 border=0>


39 隨機顯示圖像

1: <script language=”JavaScript”>
2: var imageList = new Array;
3: imageList[0] = “image1.jpg”;
4: imageList[1] = “image2.jpg”;
5: imageList[2] = “image3.jpg”;
6: imageList[3] = “image4.jpg”;
7: var imageChoice = Math.floor(Math.random() * imageList.length);
8: document.write(‘<img src=”’ + imageList[imageChoice] + ‘“>’);
9: </script>


40 函數實現的圖像替換

1: <script language=”JavaScript”>
2: var source = 0;
3: var replacement = 1;
4: function createRollOver(originalImage,replacementImage) {
5: var imageArray = new Array;
6: imageArray[source] = new Image;
7: imageArray[source].src = originalImage;
8: imageArray[replacement] = new Image;
9: imageArray[replacement].src = replacementImage;
10: return imageArray;
11: }
12: var rollImage1 = createRollOver(“image1.jpg”,”rollImage1.jpg”);
13: </script>
14: <a href=”#” onMouseOver=”document.myImage1.src = rollImage1[replacement].src;”
15: onMouseOut=”document.myImage1.src = rollImage1[source].src;”>
16: <img src="/”image1.jpg"” width=100 name=”myImage1” border=0>
17: </a>


41 創建幻燈片

1: <script language=”JavaScript”>
2: var imageList = new Array;
3: imageList[0] = new Image;
4: imageList[0].src = “image1.jpg”;
5: imageList[1] = new Image;
6: imageList[1].src = “image2.jpg”;
7: imageList[2] = new Image;
8: imageList[2].src = “image3.jpg”;
9: imageList[3] = new Image;
10: imageList[3].src = “image4.jpg”;
11: function slideShow(imageNumber) {
12: document.slideShow.src = imageList[imageNumber].src;
13: imageNumber += 1;
14: if (imageNumber < imageList.length) {
15: window.setTimeout(“slideShow(“ + imageNumber + “)”,3000);
16: }
17: }
18: </script>
19: </head>
20: <body onLoad=”slideShow(0)”>
21: <img src="/”image1.jpg"” width=100 name=”slideShow”>


42 隨機廣告圖片

1: <script language=”JavaScript”>
2: var imageList = new Array;
3: imageList[0] = “image1.jpg”;
4: imageList[1] = “image2.jpg”;
5: imageList[2] = “image3.jpg”;
6: imageList[3] = “image4.jpg”;
7: var urlList = new Array;
8: urlList[0] = “http://some.host/”;
9: urlList[1] = “http://another.host/”;
10: urlList[2] = “http://somewhere.else/”;
11: urlList[3] = “http://right.here/”;
12: var imageChoice = Math.floor(Math.random() * imageList.length);
13: document.write(‘<a href=”’ + urlList[imageChoice] + ‘“><img src=”’ + imageList[imageChoice] + ‘“></a>’);
14: </script>

JavaScript就這麼回事4:表單


還是先繼續寫完JS就這麼回事系列吧~
43 表單構成

1: <form method=”post” action=”target.html” name=”thisForm”>
2: <input type=”text” name=”myText”>
3: <select name=”mySelect”>
4: <option value=”1”>First Choice</option>
5: <option value=”2”>Second Choice</option>
6: </select>
7: <br/>
8: <input type=”submit” value=”Submit Me”>
9: </form>


44 訪問表單中的文本框內容

1: <form name=”myForm”>
2: <input type=”text” name=”myText”>
3: </form>
4: <a href='#' onClick='window.alert(document.myForm.myText.value);'>Check Text Field</a>


45 動態複製文本框內容

1: <form name=”myForm”>
2: Enter some Text: <input type=”text” name=”myText”><br/>
3: Copy Text: <input type=”text” name=”copyText”>
4: </form>
5: <a href=”#” onClick=”document.myForm.copyText.value =
6: document.myForm.myText.value;”>Copy Text Field</a>


46 偵測文本框的變化

1: <form name=”myForm”>
2: Enter some Text: <input type=”text” name=”myText” onChange=”alert(this.value);”>
3: </form>


47 訪問選中的Select

1: <form name=”myForm”>
2: <select name=”mySelect”>
3: <option value=”First Choice”>1</option>
4: <option value=”Second Choice”>2</option>
5: <option value=”Third Choice”>3</option>
6: </select>
7: </form>
8: <a href='#' onClick='alert(document.myForm.mySelect.value);'>Check Selection List</a>


48 動態增加Select項

1: <form name=”myForm”>
2: <select name=”mySelect”>
3: <option value=”First Choice”>1</option>
4: <option value=”Second Choice”>2</option>
5: </select>
6: </form>
7: <script language=”JavaScript”>
8: document.myForm.mySelect.length++;
9: document.myForm.mySelect.options[document.myForm.mySelect.length - 1].text = “3”;
10: document.myForm.mySelect.options[document.myForm.mySelect.length - 1].value = “Third Choice”;
11: </script>


49 驗證表單字段

1: <script language=”JavaScript”>
2: function checkField(field) {
3: if (field.value == “”) {
4: window.alert(“You must enter a value in the field”);
5: field.focus();
6: }
7: }
8: </script>
9: <form name=”myForm” action=”target.html”>
10: Text Field: <input type=”text” name=”myField”onBlur=”checkField(this)”>
11: <br/><input type=”submit”>
12: </form>


50 驗證Select項

1: function checkList(selection) {
2: if (selection.length == 0) {
3: window.alert(“You must make a selection from the list.”);
4: return false;
5: }
6: return true;
7: }
.

51 動態改變表單的action

1: <form name=”myForm” action=”login.html”>
2: Username: <input type=”text” name=”username”><br/>
3: Password: <input type=”password” name=”password”><br/>
4: <input type=”button” value=”Login” onClick=”this.form.submit();”>
5: <input type=”button” value=”Register” onClick=”this.form.action = ‘register.html’; this.form.submit();”>
6: <input type=”button” value=”Retrieve Password” onClick=”this.form.action = ‘password.html’; this.form.submit();”>
7: </form>


52 使用圖像按鈕

1: <form name=”myForm” action=”login.html”>
2: Username: <input type=”text” name=”username”><br/>
3: Password: <input type=”password”name=”password”><br/>
4: <input type=”image” src="/”login.gif"” value=”Login”>
5: </form>
6:


53 表單數據的加密

1: <SCRIPT LANGUAGE='JavaScript'>
2: <!--
3: function encrypt(item) {
4: var newItem = '';
5: for (i=0; i < item.length; i++) {
6: newItem += item.charCodeAt(i) + '.';
7: }
8: return newItem;
9: }
10: function encryptForm(myForm) {
11: for (i=0; i < myForm.elements.length; i++) {
12: myForm.elements[i].value = encrypt(myForm.elements[i].value);
13: }
14: }
15:
16: //-->
17: </SCRIPT>
18: <form name='myForm' onSubmit='encryptForm(this); window.alert(this.myField.value);'>
19: Enter Some Text: <input type=text name=myField><input type=submit>
20: </form>

 


JavaScript就這麼回事5:窗口和框架


54 改變瀏覽器狀態欄文字提示

1: <script language=”JavaScript”>
2: window.status = “A new status message”;
3: </script>


55 彈出確認提示框

1: <script language=”JavaScript”>
2: var userChoice = window.confirm(“Click OK or Cancel”);
3: if (userChoice) {
4: document.write(“You chose OK”);
5: } else {
6: document.write(“You chose Cancel”);
7: }
8: </script>


56 提示輸入

1: <script language=”JavaScript”>
2: var userName = window.prompt(“Please Enter Your Name”,”Enter Your Name Here”);
3: document.write(“Your Name is “ + userName);
4: </script>


57 打開一個新窗口

1: //打開一個名稱爲myNewWindow的瀏覽器新窗口
2: <script language=”JavaScript”>
3: window.open(“http://www.liu21st.com/”,”myNewWindow”);
4: </script>


58 設置新窗口的大小

1: <script language=”JavaScript”>
2: window.open(“http://www.liu21st.com/”,”myNewWindow”,'height=300,width=300');
3: </script>


59 設置新窗口的位置

1: <script language=”JavaScript”>
2: window.open(“http://www.liu21st.com/”,”myNewWindow”,'height=300,width=300,left=200,screenX=200,top=100,screenY=100');
3: </script>


60 是否顯示工具欄和滾動欄

1: <script language=”JavaScript”>
2: window.open(“http:


61 是否可以縮放新窗口的大小

1: <script language=”JavaScript”>
2: window.open('http://www.liu21st.com/' , 'myNewWindow', 'resizable=yes' );</script>


62 加載一個新的文檔到當前窗口

1: <a href='#' onClick='document.location = '125a.html';' >Open New Document</a>


63 設置頁面的滾動位置

1: <script language=”JavaScript”>
2: if (document.all) { //如果是IE瀏覽器則使用scrollTop屬性
3: document.body.scrollTop = 200;
4: } else { //如果是NetScape瀏覽器則使用pageYOffset屬性
5: window.pageYOffset = 200;
6: }</script>


64 在IE中打開全屏窗口

1: <a href='#' onClick=”window.open('http://www.juxta.com/','newWindow','fullScreen=yes');”>Open a full-screen window</a>


65 新窗口和父窗口的操作

1: <script language=”JavaScript”>
2: //定義新窗口
3: var newWindow = window.open(“128a.html”,”newWindow”);
4: newWindow.close(); //在父窗口中關閉打開的新窗口
5: </script>
6: 在新窗口中關閉父窗口
7: window.opener.close()


66 往新窗口中寫內容

1: <script language=”JavaScript”>
2: var newWindow = window.open(“”,”newWindow”);
3: newWindow.document.open();
4: newWindow.document.write(“This is a new window”);
5: newWIndow.document.close();
6: </script>


67 加載頁面到框架頁面

1: <frameset cols=”50%,*”>
2: <frame name=”frame1” src="/”135a.html"”>
3: <frame name=”frame2” src="/”about:blank"”>
4: </frameset>
5: 在frame1中加載frame2中的頁面
6: parent.frame2.document.location = “135b.html”;


68 在框架頁面之間共享腳本
如果在frame1中html文件中有個腳本

1: function doAlert() {
2: window.alert(“Frame 1 is loaded”);
3: }

那麼在frame2中可以如此調用該方法

1: <body onLoad=”parent.frame1.doAlert();”>
2: This is frame 2.
3: </body>


69 數據公用
可以在框架頁面定義數據項,使得該數據可以被多個框架中的頁面公用

1: <script language=”JavaScript”>
2: var persistentVariable = “This is a persistent value”;
3: </script>
4: <frameset cols=”50%,*”>
5: <frame name=”frame1” src="/”138a.html"”>
6: <frame name=”frame2” src="/”138b.html"”>
7: </frameset>


這樣在frame1和frame2中都可以使用變量persistentVariable
70 框架代碼庫
根據以上的一些思路,我們可以使用一個隱藏的框架頁面來作爲整個框架集的代碼庫

1: <frameset cols=”0,50%,*”>
2: <frame name=”codeFrame” src="/”140code.html"”>
3: <frame name=”frame1” src="/”140a.html"”>
4: <frame name=”frame2” src="/”140b.html"”>
5: </frameset>

 

發佈了53 篇原創文章 · 獲贊 0 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章