Strings
Breadcrumb: /javascript/strings/zombiesThis page will teach you about strings in programming.
Javascript Strings Homework
Javascript Popcorn Hack
%%javascript
let fullName = "Meryl Chen"; // <-- Add your full name
// Extract first name (characters before the space)
let spaceIndex = fullName.indexOf(" ");
let firstName = fullName.substring(0, spaceIndex); // <-- Change the numbers to get the first name correctly
// Extract last name (characters after the space)
let lastName = fullName.substring(spaceIndex + 1); // <-- Change this to get the last name correctly
// Print results
console.log("First: " + firstName);
console.log("Last: " + lastName);
<IPython.core.display.Javascript object>
Javascript Strings Homework
Task – Password Strength Checker
Write a JavaScript program that asks the user to enter a password (use prompt() in the browser).
Your program should check for these rules using string methods:
-
The password must be at least 8 characters long.
-
It must include the word “!” somewhere.
-
It must not start with a space “ “.
-
Print out one of these messages depending on the input:
-
“Strong password” if all rules are met.
-
“Weak password: too short” if less than 8 characters.
-
“Weak password: missing !” if it doesn’t include “!”.
-
“Weak password: cannot start with space” if it starts with a space.
%%js
// Example Username Checker
let username = prompt("Enter your username:");
// Rule 1: Must be at least 5 characters
if (username.length < 5) {
console.log("Invalid username: too short");
}
// Rule 2: Cannot contain spaces
else if (username.includes(" ")) {
console.log("Invalid username: no spaces allowed");
}
// Rule 3: Must start with a capital letter
else if (username[0] !== username[0].toUpperCase()) {
console.log("Invalid username: must start with a capital letter");
}
// All rules passed
else {
console.log("Valid username");
}
<IPython.core.display.Javascript object>
%%javascript
// Password Strength Checker
let password = prompt("Enter your password:");
// Handle if user presses cancel
if (password === null) {
console.log("No password entered.");
}
// Rule 1: Must be at least 8 characters long
else if (password.length < 8) {
console.log("Weak password: too short");
}
// Rule 2: Must include "!"
else if (!password.includes("!")) {
console.log("Weak password: missing !");
}
// Rule 3: Must not start with space
else if (password.startsWith(" ")) {
console.log("Weak password: cannot start with space");
}
// All rules passed
else {
console.log("Strong password");
}
<IPython.core.display.Javascript object>