Master text manipulation and string methods
Strings are sequences of characters used to represent text in JavaScript. Think of them like recipe names, ingredient lists, or cooking instructions - any text you want to work with!
Strings can be created using single quotes
('text'),
double quotes ("text"),
backticks for template literals
(`text`).
๐ก Real-World Example:
Just like a chef combines ingredients, you can combine strings to create messages, labels, or formatted text!
const recipe = "Chocolate Cake";
console.log(recipe.length); // 14 - counts all characters
const dish = "pasta carbonara";
console.log(dish.toUpperCase()); // "PASTA CARBONARA"
console.log(dish.toLowerCase()); // "pasta carbonara"
const ingredient = "Fresh Tomatoes";
console.log(ingredient.slice(0, 5)); // "Fresh"
console.log(ingredient.slice(6)); // "Tomatoes"
const recipe = "Add salt, pepper, and garlic";
console.log(recipe.includes("pepper")); // true
console.log(recipe.indexOf("garlic")); // 21
const instruction = "Bake for 20 minutes";
console.log(instruction.replace("20", "25")); // "Bake for 25 minutes"
const dish = "Pizza";
const servings = 4;
const message = `This ${dish} serves ${servings} people`;
console.log(message); // "This Pizza serves 4 people"
Write and run your own JavaScript code here:
Clean up messy recipe text! Remove extra spaces, fix capitalization, and make the recipe readable.
Search for ingredients in recipe text using string methods like includes(), slice(), and indexOf().
A messy recipe came from the kitchen! You need to clean it up by:
Input Recipe:
" add salt and pepper to taste "
Expected Output:
"Add sea salt and pepper to taste"
๐ก Hints:
.trim() to
remove spaces
.replace() to
substitute text
[0].toUpperCase()
and
.slice(1) for
capitalization
Create a function that checks if a recipe contains specific ingredients and extracts them:
Sample Recipe:
"Melt butter in a pan, then add garlic and onions"
Expected Return:
{ hasGarlic: true, butterPosition: 5, firstWord: "Melt" }
๐ก Hints:
.includes() to
check for ingredients
.indexOf() to
find positions
.split(' ') to
break into words