JavaScript String Methods
8 April 2025 | Category: JavaScript
In JavaScript, strings are a commonly used data type, and JavaScript provides many built-in string methods to manipulate them. These methods help you perform operations like changing the case, extracting parts of a string, replacing text, and more.
✅ What is a String Method?
A string method is a function that can be called on a string to perform specific actions. These are very useful for working with text data in your web applications.
🔹 1. .length
– Returns the length of a string
let text = "Hello World!";
console.log(text.length); // Output: 12
🔹 2. .toUpperCase()
– Converts to uppercase
let text = "hello";
console.log(text.toUpperCase()); // Output: "HELLO"
🔹 3. .toLowerCase()
– Converts to lowercase
let text = "HELLO";
console.log(text.toLowerCase()); // Output: "hello"
🔹 4. .slice(start, end)
– Extracts a section of the string
let text = "JavaScript";
console.log(text.slice(0, 4)); // Output: "Java"
🔹 5. .substring(start, end)
– Similar to slice
, but doesn’t accept negative values
let text = "JavaScript";
console.log(text.substring(4, 10)); // Output: "Script"
🔹 6. .replace(oldValue, newValue)
– Replaces first occurrence
let text = "I love JavaScript!";
console.log(text.replace("JavaScript", "Coding")); // Output: "I love Coding!"
⚠️ Note:
replace()
is case-sensitive. UsereplaceAll()
or regex for replacing multiple or case-insensitive matches.
🔹 7. .trim()
– Removes extra whitespace from both ends
let text = " Hello World! ";
console.log(text.trim()); // Output: "Hello World!"
🔹 8. .charAt(index)
– Returns the character at a specific index
let text = "Hello";
console.log(text.charAt(1)); // Output: "e"
🔹 9. .split(separator)
– Splits the string into an array
let text = "Apple, Banana, Mango";
let fruits = text.split(", ");
console.log(fruits); // Output: ["Apple", "Banana", "Mango"]
✨ Bonus: Chaining Methods
You can also chain string methods together:
let result = " hello world! ".trim().toUpperCase();
console.log(result); // Output: "HELLO WORLD!"
🧠 Summary
Method | Description |
---|---|
.length | Returns string length |
.toUpperCase() | Converts string to uppercase |
.toLowerCase() | Converts string to lowercase |
.slice() | Extracts part of the string |
.replace() | Replaces part of the string |
.trim() | Removes spaces from both ends |
.charAt() | Gets character at a position |
.split() | Converts string into array |