JavaScript/Regular expressions/Exercises

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Topic: Regular Expressions

1. Does the password "kw8h_rt" contain a digit?

Click to see solution
"use strict";
const myVar = "kw8h_rt";
if (myVar.match(/\d/)) {
  alert("Password is ok.");
} else {
  alert("Your password does not contain a digit.");
}



2. Be creative! Define a rule for passwords, read a password from the user using prompt, and check it.

Click to see solution
"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. Does the sentence "Kim and Maren are friends." contains the word "are"?

Click to see solution
"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. Be creative! Read strings from the user (prompt) that match the following regular expressions:

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

Discuss the meaning of the above REs with your colleague.

Click to see solution
"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. Normalize the phone number "0800 123-456-0" by stripping out all non-numerical characters.

Click to see solution
"use strict";
const myVar = "0800 123-456-0";
const result = myVar.replace(/\D/g, "");
alert(result);



6. Split the following sentences into an array that contains only its words.

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

Click to see solution
"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);