๐Ÿ“

JavaScript Strings

Master text manipulation and string methods

โญ Beginner Friendly

What are Strings?

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!

Common String Operations

1. String Length

const recipe = "Chocolate Cake";
console.log(recipe.length); // 14 - counts all characters

2. Changing Case

const dish = "pasta carbonara";
console.log(dish.toUpperCase()); // "PASTA CARBONARA"
console.log(dish.toLowerCase()); // "pasta carbonara"

3. Extracting Parts (Slice)

const ingredient = "Fresh Tomatoes";
console.log(ingredient.slice(0, 5)); // "Fresh"
console.log(ingredient.slice(6));    // "Tomatoes"

4. Searching in Strings

const recipe = "Add salt, pepper, and garlic";
console.log(recipe.includes("pepper")); // true
console.log(recipe.indexOf("garlic"));  // 21

5. Replacing Text

const instruction = "Bake for 20 minutes";
console.log(instruction.replace("20", "25")); // "Bake for 25 minutes"

6. Template Literals

const dish = "Pizza";
const servings = 4;
const message = `This ${dish} serves ${servings} people`;
console.log(message); // "This Pizza serves 4 people"

Learn More

๐Ÿš€ Try It Yourself

Write and run your own JavaScript code here:

Output:

๐Ÿ”“

Game 1: Chef Decoder

Clean up messy recipe text! Remove extra spaces, fix capitalization, and make the recipe readable.

๐Ÿ”

Game 2: Ingredient Scanner

Search for ingredients in recipe text using string methods like includes(), slice(), and indexOf().

๐Ÿ”

Challenge 1: Chef Decoder

๐Ÿ“‹ Your Mission:

A messy recipe came from the kitchen! You need to clean it up by:

  1. Removing extra spaces at the start and end
  2. Converting to proper case (capitalize first letter)
  3. Replacing "Salt" with "Sea Salt"

Input Recipe:

" add salt and pepper to taste "

Expected Output:

"Add sea salt and pepper to taste"

๐Ÿ’ก Hints:

  • Use .trim() to remove spaces
  • Use .replace() to substitute text
  • Use [0].toUpperCase() and .slice(1) for capitalization

Test Results:

๐Ÿ”Ž

Challenge 2: Ingredient Scanner

๐Ÿ“‹ Your Mission:

Create a function that checks if a recipe contains specific ingredients and extracts them:

  1. Check if the recipe includes "garlic"
  2. Find the position of "butter" in the recipe
  3. Extract the first word of the recipe

Sample Recipe:

"Melt butter in a pan, then add garlic and onions"

Expected Return:

{ hasGarlic: true, butterPosition: 5, firstWord: "Melt" }

๐Ÿ’ก Hints:

  • Use .includes() to check for ingredients
  • Use .indexOf() to find positions
  • Use .split(' ') to break into words

Test Results: