🟢 Strings & String Methods
Strings are used to represent text in JavaScript.
Examples:
const name = "Rahul";
const city = "Pune";
const message = "Welcome to JavaScript";
Strings are used everywhere:
• User names
• Emails
• Search queries
• API responses
• Messages
• URLs
• Form inputs
• File names
Understanding string manipulation is therefore essential.
1️⃣ Creating Strings
JavaScript provides three common ways to create strings.
• Double quotes:
const name = "Rahul";
• Single quotes:
const name = 'Rahul';
• Template literals:
const name = `Rahul`;
Template literals use backticks.
They become especially useful when inserting variables into strings.
2️⃣ String Length
Use
.length to find the number of characters.const message = "JavaScript";
console.log(message.length); // 10
Spaces are also counted.
const message = "Hello World";
console.log(message.length); // 11 - space is included
3️⃣ Accessing Characters
Strings use zero-based indexing, just like arrays.
const language = "JavaScript";
console.log(language[0]); // J
console.log(language[4]); // S
console.log(language[language.length - 1]); // t - last character
4️⃣ Strings Are Immutable
Strings cannot be changed directly.
const name = "Rahul";
name[0] = "K"; // Does NOT work
Instead, you create a new string:
const name = "Rahul";
const updatedName = "K" + name.slice(1);
console.log(updatedName); // Kahul
This concept of immutability is important when working with strings.
🔹 Changing Letter Case
5️⃣
toUpperCase()Converts a string to uppercase.
const name = "rahul";
console.log(name.toUpperCase()); // RAHUL
6️⃣
toLowerCase()Converts a string to lowercase.
const name = "RAHUL";
console.log(name.toLowerCase()); // rahul
A common real-world use:
const userInput = "ADMIN";
if (userInput.toLowerCase() === "admin") {
console.log("Admin user");
}
🔹 Removing Unwanted Spaces
7️⃣
trim()trim() removes whitespace from the beginning and end of a string.const name = " Rahul ";
console.log(name.trim()); // Rahul
This is extremely useful when processing form inputs.
8️⃣
trimStart()Removes whitespace from the beginning.
const text = " Hello";
console.log(text.trimStart()); // "Hello"
9️⃣
trimEnd()Removes whitespace from the end.
const text = "Hello ";
console.log(text.trimEnd()); // "Hello"
🔹 Searching Strings
🔟
includes()Checks whether a string contains specific text.
const message = "Welcome to JavaScript";
console.log(message.includes("JavaScript")); // true
const email = "user@gmail.com";
console.log(email.includes("@")); // true
1️⃣1️⃣
startsWith()Checks whether a string starts with specific text.
const url = "https://example.com";
console.log(url.startsWith("https")); // true
1️⃣2️⃣
endsWith()Checks whether a string ends with specific text.