Date型別和Regex型別

gecko23發表於2014-10-15

Date 型別

var now = new Date();

在呼叫Date建構函式而不傳遞引數的情況下,新建立的物件自動獲得當前日期和時間

特定的日期和時間建立日期物件,必須傳入表示該日期的毫秒數(即從UTC時間1970年1月1日午
夜起至該日期止經過的毫秒數)

Date.parse()方法接收一個表示日期的字串引數,然後嘗試根據這個字串返回相應日期的毫秒數

要為2004年5月25日建立一個日期物件,可以使用下面的程式碼:

var someDate = new Date(Date.parse("May 25, 2004")); 

Date.parse()方法的字串不能表示日期,那麼它會返回NaN。實際上,如果直接將表
示日期的字串傳遞給Date建構函式,也會在後臺呼叫Date.parse()。

換句話說,下面的程式碼與前面的例子是等價的:

var someDate = new Date("May 25, 2004"); 

這行程式碼將會得到與前面相同的日期物件

Data.now()
返回表示呼叫這個方法時的日期和時間的毫秒數

Date型別也重寫了toLocaleString()、toString()和valueOf()

toLocaleString()、toString()

這兩個方法在不同的瀏覽器中返回的日期和時間格式可謂大相徑庭。

valueOf()方法,則根本不返回字串,而是返回日期的毫秒錶示

RegExp 型別

var expression = /pattern/ flags ;

g:表示全域性(global)模式,即模式將被應用於所有字串,而非在發現第一個匹配項時立即停止;

 i:表示不區分大小寫(case-insensitive)模式,即在確定匹配項時忽略模式與字串的大小寫;

 m:表示多行(multiline)模式,即在到達一行文字末尾時還會繼續查詢下一行中是否存在與模式匹配的項。

所有元字元都必須轉義。
正規表示式中的元字元包括:( [ { \ ^ $ | ) ? * + .]}

可以使用字面量定義的任何表示式,
可以使用建構函式來定義,

var pattern1 = /[bc]at/i; 

var pattern2 = new RegExp("[bc]at", "i"); 

RegExp的每個例項都具有下列屬性,透過這些屬性可以取得有關模式的各種資訊。

 global:布林值,表示是否設定了g標誌。
 ignoreCase:布林值,表示是否設定了i標誌。
 lastIndex:整數,表示開始搜尋下一個匹配項的字元位置,從0算起。
 multiline:布林值,表示是否設定了m標誌。
 source:正規表示式的字串表示,按照字面量形式而非傳入建構函式中的字串模式返回。

    var pattern1 = /\[bc\]at/i; 
    alert(pattern1.global); //false 
    alert(pattern1.ignoreCase); //true 
    alert(pattern1.multiline); //false 
    alert(pattern1.lastIndex); //0 
    alert(pattern1.source); //"\[bc\]at" 

RegExp物件的主要方法是exec(),

該方法是專門為捕獲組而設計的。
exec()接受一個引數,即要應用模式的字串,
然後返回包含第一個匹配項資訊的陣列;或者在沒有匹配項的情況下返回null。
返回的陣列雖然是Array的例項,但包含兩個額外的屬性:index和input。
其中,index表示匹配項在字串中的位置,
而input表示應用正規表示式的字串。

在陣列中,第一項是與整個模式匹配的字串,
其他項是與模式中的捕獲組匹配的字串(如果模式中沒有捕獲組,則該陣列只包含一項)。
請看下面的例子。
var text = "mom and dad and baby";
var pattern = /mom( and dad( and baby)?)?/gi;
var matches = pattern.exec(text);
console.log(matches.index); // 0
console.log(matches.input); // "mom and dad and baby"
console.log(matches[0]); // "mom and dad and baby"
console.log(matches[1]); // " and dad and baby"
console.log(matches[2]); // " and baby"

對於exec()方法而言,即使在模式中設定了全域性標誌(g),它每次也只會返回一個匹配項。在不
設定全域性標誌的情況下,在同一個字串上多次呼叫exec()將始終返回第一個匹配項的資訊。而在設
置全域性標誌的情況下,每次呼叫exec()則都會在字串中繼續查詢新匹配項,如下面的例子所示。

var text = "cat, bat, sat, fat"; 
var pattern1 = /.at/; 
var matches = pattern1.exec(text); 
alert(matches.index); //0 
alert(matches[0]); //cat 
alert(pattern1.lastIndex); //0 
matches = pattern1.exec(text); 
alert(matches.index); //0 
alert(matches[0]); //cat 
alert(pattern1.lastIndex); //0 


var pattern2 = /.at/g; 
var matches = pattern2.exec(text); 
alert(matches.index);  //0 
alert(matches[0]); //cat 
alert(pattern2.lastIndex); //3 

matches = pattern2.exec(text); 
alert(matches.index); //5 
alert(matches[0]); //bat 
alert(pattern2.lastIndex); //8 

相關文章