跳至內容

JavaScript/正則表示式/練習

來自華夏公益教科書,開放的書籍,開放的世界

主題:正則表示式

1. 密碼 "kw8h_rt" 是否包含數字?

點選檢視解決方案
"use strict";
const myVar = "kw8h_rt";
if (myVar.match(/\d/)) {
  alert("Password is ok.");
} else {
  alert("Your password does not contain a digit.");
}



2. 發揮創意!定義一個密碼規則,使用prompt從使用者那裡讀取密碼,並對其進行檢查。

點選檢視解決方案
"use strict";

// for example:
const pw = prompt("Please enter your password (must contain two characters which are NOT alphanumeric).");

if (pw.match(/\W.*\W/)) {
  alert("Your password is ok.");
} else {
  alert("Your password does not conform to the rules.");
}



3. 句子 "Kim and Maren are friends." 是否包含單詞 "are"?

點選檢視解決方案
"use strict";
const myVar = "Kim and Maren are friends.";
alert(myVar.match(/are/));  // looks good, but:

// consider word boundaries
alert(myVar.match(/\bare\b/));
// ... proof:
alert(myVar.match(/are.*/));



4. 發揮創意!從使用者那裡讀取與以下正則表示式匹配的字串 (prompt)

  • d\dd
  • d\d+d
  • \bwhy\b
  • x\s-\sy\s=\sz

與同事討論上述 RE 的含義。

點選檢視解決方案
"use strict";

// for example:
const myVar = prompt("What string conforms to the RE /d\dd/?");

if (myVar.match(/d\dd/)) {
  alert("Bingo.");
} else {
  alert("Sorry.");
}



5. 透過去除所有非數字字元來規範化電話號碼 "0800 123-456-0"。

點選檢視解決方案
"use strict";
const myVar = "0800 123-456-0";
const result = myVar.replace(/\D/g, "");
alert(result);



6. 將以下句子拆分為僅包含其單詞的陣列。

"Tom cried: 'What the hell is going on?'. Then he left the room."

點選檢視解決方案
"use strict";
const sentence = "Tom cried: 'What the hell is going on?'. Then he left the room."
const arr = sentence.split(/\W+/);  // one or more non-alphanumeric characters
alert(arr);
華夏公益教科書