String Methods
What Are String Methods?
You already know how to create strings and combine them. But strings can do so much more! JavaScript gives you string methods — built-in tools that let you transform, search, and slice text.
To use a method, put a dot . after a string (or a variable holding a string), then the method name with parentheses:
HELLO
Changing Case
Use .toUpperCase() and .toLowerCase() to change all letters to uppercase or lowercase:
ALICE alice
Cleaning Up Strings
Use .trim() to remove extra spaces from the beginning and end:
hello
There's also .trimStart() (start only) and .trimEnd() (end only).
Replacing Text
Use .replaceAll(old, new) to swap every occurrence in a string:
I like dogs
Careful: plain .replace() only swaps the first match. Use .replaceAll() when you want them all!
Splitting and Joining
.split(" ") breaks a string into an array of words:
3
You can split on any character:
red
.join() does the opposite — it glues an array into one string:
hello world
Searching in Strings
Use .indexOf() to get the position of text inside a string. It returns -1 if not found:
6 -1
To count how many times something appears, here's a handy trick — split on it and count the pieces:
3
Checking Start and End
.startsWith() and .endsWith() return true or false:
true false
Checking What a String Contains
Use .includes() to check if a string contains another string:
true false
String Slicing
You can grab parts of a string with .slice(start, end):
Pyt thon Pyth
A negative start counts from the end:
hon
To reverse a string, split it into characters, reverse the array, and join it back:
olleh
Chaining Methods
You can chain methods together — each one works on the result of the previous one:
hello-world