Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

JavaScript/Regular expressions/Exercises

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

Topic: Regular Expressions 1. Does the password "kw8h_rt" contain a digit? 100% "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. 100% "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"? 100% "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. 100% "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. 100% "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." 100% "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);