Web Development - HTML, CSS & JavaScript
const fileName = "report.pdf";
console.log(fileName.endsWith(".pdf")); // true
🔹 Finding Positions
1️⃣3️⃣ indexOf()
Returns the position of the first occurrence.
const message = "Hello JavaScript";
console.log(message.indexOf("JavaScript")); // 6
console.log(message.indexOf("Python")); // -1 - not found
1️⃣4️⃣ lastIndexOf()
Returns the position of the last occurrence.
const text = "JavaScript is powerful. JavaScript is popular.";
console.log(text.lastIndexOf("JavaScript")); // 25
🔹 Extracting Parts of a String
1️⃣5️⃣ slice()
slice() extracts part of a string.
const language = "JavaScript";
console.log(language.slice(0, 4)); // Java
The ending index is not included.
• 0 → J
• 1 → a
• 2 → v
• 3 → a
• 4 → S
• So slice(0, 4) returns characters from index 0 through 3.
1️⃣6️⃣ Negative Indexes
You can use negative indexes with slice().
const language = "JavaScript";
console.log(language.slice(-6)); // Script
🔹 substring()
1️⃣7️⃣ substring()
substring() can also extract part of a string.
const language = "JavaScript";
console.log(language.substring(0, 4)); // Java
For modern JavaScript code, slice() is often more convenient because it supports negative indexes.
🔹 Replacing Text
1️⃣8️⃣ replace()
Replaces the first matching occurrence.
const message = "I like JavaScript";
const updated = message.replace("JavaScript", "Python");
console.log(updated); // I like Python
1️⃣9️⃣ replaceAll()
Replaces all matching occurrences.
const message = "JavaScript is great. JavaScript is popular.";
const updated = message.replaceAll("JavaScript", "JS");
console.log(updated); // JS is great. JS is popular.
🔹 Splitting Strings
2️⃣0️⃣ split()
split() converts a string into an array.
const names = "Amit,Priya,Rahul";
const result = names.split(",");
console.log(result); // ["Amit", "Priya", "Rahul"]
const sentence = "Learn JavaScript step by step";
const words = sentence.split(" ");
console.log(words); // ["Learn", "JavaScript", "step", "by", "step"]
🔹 Joining Data
2️⃣1️⃣ join()
join() combines array elements into a string.
const words = ["Learn", "JavaScript"];
const sentence = words.join(" ");
console.log(sentence); // Learn JavaScript
Notice:
• split() → string → array
• join() → array → string
⭐ Template Literals
2️⃣2️⃣ What Are Template Literals?
Template literals use backticks:
const message = `Hello`;
Their biggest advantage is easy string interpolation.
const name = "Rahul";
const age = 25;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // My name is Rahul and I am 25 years old.
2️⃣3️⃣ Expressions Inside Template Literals
You can also use expressions.
const price = 1000;
const quantity = 3;
const total = `Total: ${price * quantity}`;
console.log(total); // Total: 3000
2️⃣4️⃣ Multi-line Strings
Template literals make multi-line text easier.
const message = `
Hello Rahul,
Welcome to JavaScript.
Keep learning!
`;
console.log(message);
4 · 1.2K ·