Strings, Numbers & MathExtra· 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

MethodDoes
.lengthNumber 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.

Chaining string methods
<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

  1. Take a messy string with extra spaces and clean + uppercase it.
  2. Use .split(",") to turn "a,b,c" into an array.

🏠 Homework

  1. Write a function that takes a full name and returns the initials (hint: split + slice).
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →