返回課程

HTML 顏色的正規表示法

建立一個正規表示法來搜尋寫成 #ABCDEF 的 HTML 顏色:首先是 #,然後是 6 個十六進位字元。

使用範例

let regexp = /...your regexp.../

let str = "color:#121212; background-color:#AA00ef bad-colors:f#fddee #fd2 #12345678";

alert( str.match(regexp) )  // #121212,#AA00ef

P.S. 在這個任務中,我們不需要其他顏色的格式,例如 #123rgb(1,2,3) 等。

我們需要尋找 # 後面接著 6 個十六進位字元。

十六進位字元可以用 [0-9a-fA-F] 來描述。或者,如果我們使用 i 旗標,則只需 [0-9a-f]

然後,我們可以使用量詞 {6} 來尋找 6 個這樣的字元。

因此,我們有正規表示法:/#[a-f0-9]{6}/gi

let regexp = /#[a-f0-9]{6}/gi;

let str = "color:#121212; background-color:#AA00ef bad-colors:f#fddee #fd2"

alert( str.match(regexp) );  // #121212,#AA00ef

問題在於它會在較長的序列中找到顏色

alert( "#12345678".match( /#[a-f0-9]{6}/gi ) ) // #123456

要修正這個問題,我們可以在結尾加上 \b

// color
alert( "#123456".match( /#[a-f0-9]{6}\b/gi ) ); // #123456

// not a color
alert( "#12345678".match( /#[a-f0-9]{6}\b/gi ) ); // null