Concept Explanation
Strings are more than just text; they are "Immutable" objects with built-in superpowers. In modern JS, we use Template Literals (backticks ) which allow us to write multi-line text and inject variables directly.
Syntax or Core Structure
Template Literals vs Quotes
const name = "Alice";
// THE OLD WAY (Messy)
console.log("Hello " + name + "!");
// THE MODERN WAY (Clean)
console.log(`Hello ${name}!`);
Essential Methods
const text = " JavaScript is Awesome ";
console.log(text.trim()); // Removes spaces
console.log(text.includes("JS")); // false (It's case-sensitive!)
console.log(text.slice(0, 10)); // "JavaScript"
Best Practices
- Template Literals: Use backticks for almost everything. They are more flexible and easier to read.
- Case Normalization: When checking user input (like a search bar), always use
.toLowerCase()on both the search term and the data to ensure the match works. - Immutability: Remember that string methods return a new string. They do not change the original one.
Practice Exercises
- The Multi-liner: Create a template literal that spans 3 lines and includes at least 2 variables.
- The Search Engine: Write a function that checks if a sentence contains a "naughty word" and replaces it with stars (***).
- The Formatter: Take a user's name like " aLiCe " and turn it into "Alice" using string methods.