Strings in JavaScript
Every app you use is full of text: your name on Instagram, a WhatsApp message, an OTP, a product name on Flipkart, a train name on IRCTC. 📱
In JavaScript, text is stored as a string.
What Is a String?
📝 Definition: A string is a sequence of characters (letters, numbers, spaces, symbols, or emojis) used to store text. It is a primitive data type in JavaScript.
Think of a string like a garland of beads 📿. Each bead is one character, and the beads are kept in order on one thread.
"HELLO"
H E L L O
0 1 2 3 4 ← each character has a position (index)
Three ways to write a string
| Quotes | Example | Notes |
|---|---|---|
Double quotes " " | "Hello" | Very common |
Single quotes ' ' | 'Hello' | Same as double quotes |
Backticks ` ` | `Hello` | Template literals, with extra powers ✨ |
Useful basics
Quotes inside a string
Special characters (escape sequences)
| Code | Meaning |
|---|---|
\n | New line |
\t | Tab space |
\\ | A backslash |
\' / \" | A quote |
Part 1: Template Literals
The Old Way: Joining with +
Imagine printing a train ticket 🎫:
It works, but all those + signs and quotes are messy and easy to get wrong. 😵
The Better Way: Template Literals ✨
📝 Definition: Template literals are strings written with backticks
` `. They let you put variables and expressions directly inside the text using${ }, and they can span multiple lines.
Much cleaner! Think of it like a fill-in-the-blanks form 📝: the ${ } are the blanks, and JavaScript fills them in.
1. Putting Expressions Inside ${ }
You can put any expression inside ${ }: maths, function calls, and even ternary operators.
2. Multi-Line Strings
With normal quotes, you need \n for new lines. With backticks, just press Enter.
3. Building HTML Text (Common in Real Apps)
4. Tagged Templates (Advanced, Just a Peek 👀)
A tag is a function placed before a template literal. It gets the text parts and the values separately, so it can process them.
As a beginner, you won't write tags often. But libraries use them a lot, for example to write CSS or SQL safely.
+ vs template literals
| Point | + joining | Template literal |
|---|---|---|
| Readability | Messy with many parts | Clean ✅ |
| Expressions | Need extra brackets | Put inside ${ } |
| Multi-line | Needs \n | Just press Enter |
| Quotes inside | Need escaping | No escaping needed |
Part 2: Common String Methods
Strings come with many built-in methods, which are ready-made tools for working with text. 🧰
⚠️ Important: String methods never change the original string. They always return a new string. (You'll see why in Part 3!)
Changing Case
Real use: comparing text without worrying about capital letters.
Removing Extra Spaces: trim()
Users often type extra spaces by mistake. trim() removes spaces from both ends.
Searching Inside a String
| Method | Returns | Example |
|---|---|---|
includes(text) | true / false | Does it contain this? |
startsWith(text) | true / false | Does it start with this? |
endsWith(text) | true / false | Does it end with this? |
indexOf(text) | Position, or -1 | Where is it first found? |
lastIndexOf(text) | Position, or -1 | Where is it last found? |
Real example: checking a phone number and email
Getting Part of a String: slice()
slice(start, end) cuts out a piece. The end index is not included (just like arrays).
Real example: hiding a card number 💳
substring(start, end)works almost the same asslice(), but it doesn't support negative numbers. Preferslice().
Replacing Text
Both methods are case-sensitive:
"Tea"and"tea"are different.
Splitting and Joining
split() breaks a string into an array. join() (an array method) puts the pieces back together.
Repeating and Padding
Real example: order and roll numbers
Reading Characters
Chaining Methods 🔗
Because each method returns a new string, you can connect them one after another.
Quick Methods Table
| Method | What it does | Example | Result |
|---|---|---|---|
length | Counts characters | "Hi".length | 2 |
toUpperCase() | All capitals | "hi".toUpperCase() | "HI" |
toLowerCase() | All small letters | "HI".toLowerCase() | "hi" |
trim() | Removes outer spaces | " hi ".trim() | "hi" |
includes() | Contains? | "hello".includes("ell") | true |
startsWith() | Starts with? | "hello".startsWith("he") | true |
endsWith() | Ends with? | "hello".endsWith("lo") | true |
indexOf() | Position of text | "hello".indexOf("l") | 2 |
slice() | Cuts a part | "hello".slice(1, 3) | "el" |
replace() | Replaces the first match | "aa".replace("a", "b") | "ba" |
replaceAll() | Replaces all matches | "aa".replaceAll("a", "b") | "bb" |
split() | String → array | "a,b".split(",") | ["a", "b"] |
repeat() | Repeats text | "ab".repeat(2) | "abab" |
padStart() | Pads at the start | "5".padStart(2, "0") | "05" |
at() | Character at a position | "hello".at(-1) | "o" |
Part 3: String Immutability
📝 Definition: Immutable means "cannot be changed." In JavaScript, strings are immutable: once a string is created, its characters can never be changed. Every string method gives you a new string instead.
Think of a string like a printed newspaper 📰. You can't change the letters printed on it. If you want different text, you have to print a new newspaper.
You can't change a character directly
JavaScript simply ignores this. (In strict mode, it even throws an error.)
Methods don't change the original
⚠️ Most common beginner mistake: calling a string method and forgetting to save the result.
So how do we "change" a string?
We create a new string and store it in the variable. The variable can point to a new string, but the old string itself never changes.
It's like writing a new name tag 🏷️ and sticking it on the box. The old tag isn't edited; it's replaced.
Variable vs value: let vs const
| Can you give the variable a new string? | Can you change the characters? | |
|---|---|---|
let str | ✅ Yes | ❌ No (strings are immutable) |
const str | ❌ No | ❌ No (strings are immutable) |
Strings vs arrays
Arrays can be changed in place. Strings cannot. That's a big difference!
Tip: If you need to change many characters, split the string into an array, change the array, then join it back.
Why are strings immutable? 🤔
- Safety: A string you pass to a function can never be changed by accident.
- Speed: JavaScript can safely share and reuse the same string in memory.
- Predictability: The same string always has the same value.
⚠️ Building strings in big loops
Every += creates a new string. For a few items, that's fine. For thousands of pieces, collecting them in an array and joining once is cleaner.
Part 4: String Manipulation Problems
Time to practice! 💪 For each problem, try it yourself first, then check the solution.
🟢 Problem 1: Reverse a String
Input: "India"Output: "aidnI"
💡 Idea: Split into an array of characters, reverse the array, and join it back.
🟢 Problem 2: Count Vowels
Input: "Bengaluru"Output: 4
💡 Idea: Go through each character, and count it if it's one of a, e, i, o, u.
🟢 Problem 3: Capitalise the First Letter of Each Word
Input: "welcome to namma bengaluru"Output: "Welcome To Namma Bengaluru"
💡 Idea: Split into words, capitalise the first letter of each word, then join them back.
🟢 Problem 4: Check for a Palindrome
A palindrome reads the same forwards and backwards, like "madam" or "racecar". 🔁
Input: "Madam"Output: true
💡 Idea: Clean the text (lowercase, remove spaces and symbols), then compare it with its reverse.
/[^a-z0-9]/gis a regular expression that means "any character that is NOT a letter or number." Replacing it with""removes spaces and symbols.
🟡 Problem 5: Count Words
Input: " I love learning JavaScript "Output: 4
💡 Idea: Trim the ends, then split on one or more spaces, so extra spaces don't create empty "words."
🟡 Problem 6: Find the Longest Word
Input: "I live in Thiruvananthapuram"Output: "Thiruvananthapuram"
💡 Idea: Split into words, then keep track of the longest one.
🟡 Problem 7: Count Each Character
Input: "banana"Output: { b: 1, a: 3, n: 2 }
💡 Idea: Use an object as a tally sheet ✍️.
🟡 Problem 8: Remove Duplicate Characters
Input: "programming"Output: "progamin"
💡 Idea: A Set keeps only unique values, and it remembers the order they first appeared in.
🟡 Problem 9: Check if Two Words Are Anagrams
Anagrams have the same letters in a different order, like "listen" and "silent".
💡 Idea: Sort the letters of both words. If the sorted versions match, they are anagrams.
🔴 Problem 10: Compress a String
Input: "aaabbcddd"Output: "a3b2c1d3"
💡 Idea: Walk through the string, counting how many times the same character repeats in a row. When the character changes, save the character and its count.
🔴 Problem 11: First Non-Repeating Character
Input: "aabbcdeec"Output: "d"
💡 Idea: Count all characters first. Then find the first one whose count is 1.
🔴 Problem 12: Convert to camelCase
Input: "total-cart-price" or "total cart price"Output: "totalCartPrice"
💡 Idea: Split on spaces, -, or _. Keep the first word in lowercase, and capitalise the first letter of every other word.
🎯 Practice Challenges (Try Yourself!)
- Count a specific letter: How many times does
"a"appear in"Ahmedabad"? (Ignore case.) - Mask an email:
"[email protected]"→"p****@gmail.com" - Truncate text: If a string is longer than 20 characters, cut it and add
"...". - Reverse each word:
"Hello World"→"olleH dlroW" - Check a strong password: at least 8 characters, with a number and a capital letter.
- Snake case:
"totalCartPrice"→"total_cart_price"
Common Mistakes to Avoid
| Mistake | Problem | Fix |
|---|---|---|
str.toUpperCase(); without saving | The original doesn't change | str = str.toUpperCase(); |
str[0] = "X" | Silently ignored (strings are immutable) | Build a new string: "X" + str.slice(1) |
Using ' quotes around 'It's' | ❌ SyntaxError | Use "It's" or backticks |
Writing "${name}" with normal quotes | Prints ${name} literally | Use backticks: `${name}` |
Expecting replace() to change all matches | Only the first changes | Use replaceAll() |
Comparing "Delhi" === "delhi" | false (case-sensitive) | Compare with .toLowerCase() |
"5" + 5 | "55" (text joining) | Convert first: Number("5") + 5 |
Quick Summary Table
| Task | Code |
|---|---|
| Insert a variable | `Hello, ${name}` |
| Multi-line text | Backticks + Enter |
| Length | str.length |
| Uppercase / lowercase | str.toUpperCase() / str.toLowerCase() |
| Remove outer spaces | str.trim() |
| Check for text | str.includes("x") |
| Cut a part | str.slice(start, end) |
| Replace all | str.replaceAll("a", "b") |
| String → array | str.split(" ") |
| Array → string | arr.join(" ") |
| Reverse | str.split("").reverse().join("") |
| Pad with zeros | str.padStart(3, "0") |
Key Takeaways
- A string is a sequence of characters used to store text. Write it with
" ",' ', or backticks` `. - Template literals (backticks) let you insert values with
${ }and write multi-line text easily. - Strings have many helpful methods, like
trim,includes,slice,replaceAll,split, andpadStart, and you can chain them together. - Strings are immutable: their characters can never change. Every method returns a new string, so always save the result.
- Most string problems use a few tricks: split → change → join, tally objects for counting, and Sets for unique characters.