Strings, Numbers & Math›Extra· 30 min read
String Methods
Built-in tools to measure, change, search and slice text.
What you will learn
- Use common string methods
- Search within strings
- Transform text
The everyday methods
| Method | Does |
|---|---|
.length | Number of characters |
.toUpperCase() / .toLowerCase() | Change case |
.includes("x") | Does it contain x? (true/false) |
.indexOf("x") | Position of x (or -1) |
.slice(0, 3) | Cut out part of the text |
.replace("a","b") | Replace text |
.trim() | Remove spaces at the ends |
.split(",") | Break into an array |
Below, text has deliberate extra spaces at both ends. We use a few methods on it and print the results.
<script>
let text = " CodingClave ";
document.write(text.trim().toUpperCase() + "<br>");
document.write("Length: " + text.trim().length + "<br>");
document.write("Has 'Clave'? " + text.includes("Clave"));
</script>Live preview
Line by line: text.trim() removes the surrounding spaces (giving "CodingClave"), then .toUpperCase() shouts it in capitals. text.trim().length counts the characters after trimming — 11. text.includes("Clave") asks "is the word Clave in there?" and answers true.
Note: Output: CODINGCLAVE Length: 11 Has 'Clave'? true
Tip: Methods can be chained: text.trim().toUpperCase() trims first, then upper-cases the result. Read left to right.
Q. Which method removes spaces from the start and end of a string?
Answer: .trim() removes leading and trailing whitespace — very common when handling form input.
✍️ Practice
- Take a messy string with extra spaces and clean + uppercase it.
- Use
.split(",")to turn "a,b,c" into an array.
🏠 Homework
- Write a function that takes a full name and returns the initials (hint:
split+slice).