In JavaScript, strings come with built-in methods that allow you to manipulate and inspect text easily. Understanding these methods helps in tasks like searching, modifying, and formatting strings.

💡 What are String Methods?
String methods are functions available on string values to perform operations such as finding substrings, changing case, trimming spaces, and more.
Common String Methods
| Method | Description | Example (" Hello ") |
|---|---|---|
length | Property returning the total number of characters in the string. | " Hello ".length → 7 |
toUpperCase() | Returns a new string with all characters converted to uppercase. | " Hello ".toUpperCase() → " HELLO " |
toLowerCase() | Returns a new string with all characters converted to lowercase. | " Hello ".toLowerCase() → " hello " |
trim() | Returns a new string with whitespace removed from both ends. | " Hello ".trim() → "Hello" |
indexOf(str) | Returns the starting index of a substring (returns -1 if not found). | " Hello ".indexOf("e") → 2 |
includes(str) | Returns true if the string contains the substring, otherwise false. | " Hello ".includes("ll") → true |
slice(start, end) | Extracts a portion of a string from start index up to end index. | " Hello ".slice(1, 5) → "Hell" |
replace(old, new) | Returns a new string with the first occurrence of a substring replaced. | " Hello ".replace("H", "Y") → " Yello " |
split(sep) | Splits the string into an array of substrings based on the separator. | " Hello ".split("e") → [" H", "llo "] |
📌 Deep Dive: Using Popular String Methods
const message = " Hello, JavaScript! ";
console.log(message.length); // 22 (includes spaces)
console.log(message.trim()); // "Hello, JavaScript!"
console.log(message.toUpperCase()); // " HELLO, JAVASCRIPT! "
console.log(message.toLowerCase()); // " hello, javascript! "
console.log(message.indexOf("Java")); // 8
console.log(message.includes("script")); // true
console.log(message.slice(2, 7)); // "Hello"
console.log(message.replace("JavaScript", "JS")); // " Hello, JS! "
console.log(message.trim().split(", ")); // ["Hello", "JavaScript!"]
"Hello, JavaScript!"
" HELLO, JAVASCRIPT! "
" hello, javascript! "
8
true
"Hello"
" Hello, JS! "
["Hello", "JavaScript!"]
💡 Remember:
Strings in JavaScript are immutable. Methods like toUpperCase() and replace() return new strings—they do not change the original.
⚠️ Common Pitfall
Using indexOf() to check if a substring exists requires checking for >= 0, because it returns -1 if not found. For clarity, prefer includes() which returns a boolean.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which method returns the position of a substring inside a string?
Question 2 of 2
What does the trim() method do?
Loading results...