跳至内容

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);
华夏公益教科书