Hi all,
--What is a String?
A string is just text. It is a bunch of characters linked together. Characters can be letters, numbers, symbols, or even blank spaces. In JavaScript, we use strings to store and change text data, like a user's name or an email address.
--How to Create a String?
You can make a string by wrapping your text in quotes. JavaScript gives you three different ways to do this:
-Single Quotes: 'Hello'
-Double Quotes: "Hello"
-Backticks: Hello
Single and double quotes do the exact same thing.
--The Power of Backticks:
Backticks are special. They let you do two cool things that normal quotes cannot do:
Multi-line text: You can hit "Enter" and type on a new line without breaking your code.
Insert variables: You can plug a variable straight into your text using ${variableName}. This is called interpolation.
EXAMPLE:
let name = "Alex";
let greeting = Hello, ${name}! ;
Welcome back.
--Strings Cannot Be Changed:
In JavaScript, strings are immutable. This is a fancy word that means "unchangeable."
Once you create a string, you cannot change a single letter of it directly. If you try to fix a typo or modify the text, JavaScript will actually leave the original string alone and create a brand-new string for you.
--Counting Characters:
Every string has a built-in counter called length. It tells you exactly how many characters are inside that string, including spaces and punctuation.
EXAMPLE:
let word = "Cat";
console.log(word.length); // This prints: 3
--How Strings are Indexed?
JavaScript counts string positions starting from 0, not 1.
-The first letter is at position 0.
-The second letter is at position 1.
-The third letter is at position 2.
If you want to grab just one letter, you can use square brackets with the position number: word[0].
Helpful String Tools:
JavaScript has built-in tools (called methods) to help you change or inspect your text. Here are the most useful ones:
-toLowerCase(): Makes the whole string lowercase.
-toUpperCase(): Makes the whole string uppercase.
-trim(): Cuts off any accidental spaces at the very beginning or very end.
-includes(): Checks if a specific word or letter is hidden inside your text (returns true or false).
-replace(): Swaps out a piece of text for something new.
EXAMPLE:
javascriptlet input = " jAvAsCrIpT ";
// 1. Clean up the spaces
let cleanInput = input.trim(); // "jAvAsCrIpT"
// 2. Make it lowercase
let lowerInput = cleanInput.toLowerCase(); // "javascript"
// 3. Check if it contains "script"
let hasScript = lowerInput.includes("script"); // true
Top comments (0)