Topic 38 of 87
String Modification
Overview
JavaScript provides built-in methods to change the casing of a string, remove whitespace, or pad it with characters.
Crucial Concept: Strings in JavaScript are IMMUTABLE. This means these methods never alter the original string. They always generate and return a brand new string. If you don't save the result to a variable, the modification is lost.
Syntax
Casing and Whitespace
javascript
const rawInput = " Hello World! ";
// Changing Case
console.log(rawInput.toUpperCase()); // " HELLO WORLD! "
console.log(rawInput.toLowerCase()); // " hello world! "
// Trimming removes whitespace from BOTH ends
console.log(rawInput.trim()); // "Hello World!"
// You can chain methods!
const cleanStr = rawInput.trim().toLowerCase(); // "hello world!"Padding (ES2017)
javascript
const invoiceId = "5";
// padStart(targetLength, padString)
console.log(invoiceId.padStart(4, "0")); // "0005"
console.log(invoiceId.padEnd(4, "X")); // "5XXX"Common Pitfalls
- Assuming
trim()modifies the original variable. If you writeemailInput.trim();without assigning it,emailInputremains full of spaces! You must writeemailInput = emailInput.trim();.
Interview Questions
Q:
What does it mean that strings are 'immutable' in JavaScript?
A:
Immutability means that once a string is created, its value cannot be changed in memory. String methods like .toUpperCase() do not modify the original string; they create and return a completely new string.
Real-World Example
Standardizing a user's email input during login so that 'User@Gmail.com' matches 'user@gmail.com' in the database.
example
javascript
const safeEmail = emailInput.value.trim().toLowerCase();
login(safeEmail);Check Your Knowledge
Test your understanding of String Modification with these quick questions.