Introduction
Most of the data a program touches is text: names, messages, addresses, search terms. Numbers need care too, particularly when you show them to people. This lesson collects the tools you will use every day, so that you can clean up messy input and show results neatly.
How it works
Strings are read-only. You can read a character with word[0] or word.at(-1) (the last one), but you cannot change a character in place. Every string method gives back a new string, and the original stays as it was. That is why you must keep the result: name = name.trim();.
| Method | What it gives |
|---|---|
s.length | the number of characters (with no brackets) |
s.toUpperCase(), s.toLowerCase() | the text in another case |
s.trim() | the text without spaces at both ends |
s.includes("x"), s.startsWith("x") | true or false |
s.indexOf("x") | where it first appears, or -1 |
s.slice(a, b) | the characters from a up to, but not including, b |
s.replace("a", "b") | the first match replaced; replaceAll does every one |
s.split(" ") | a list of the pieces between the spaces |
s.repeat(3), s.padStart(5, "0") | repeated or padded text |
A list made by split can be walked with for...of from the last lesson, and list.join(", ") glues the pieces back together. You will study lists properly in the arrays lesson.
Numbers. The Math object holds common calculations. Math.round, Math.floor and Math.ceil round to the nearest whole number, down and up. Math.max and Math.min find the largest and smallest of their arguments, Math.abs removes the sign, and 2 ** 10 is 2 to the power of 10.
Formatting. price.toFixed(2) gives exactly two decimal places, which suits money, and rounds as it does so. Its result is a string, because it is meant for showing.
Reading numbers from text. Number("12px") is NaN because the whole text must be a number. parseInt("12px") and parseFloat("12.5kg") read as much as they can from the start, which suits values such as CSS sizes.
Characters are numbers underneath. "A".charCodeAt(0) is 65, and String.fromCharCode(66) is "B". Letters have consecutive codes, so you can do arithmetic on them. Run this example to see the number tools together:
// Rounding, converting and formatting numbers.
const price = 1234.5678;
console.log(Math.round(price), Math.floor(price), Math.ceil(price));
console.log(price.toFixed(2), typeof price.toFixed(2));
console.log(Number("12.5"), Number("12px"), parseInt("12px"), parseFloat("12.5kg"));
console.log(Math.max(3, 9, 4), Math.min(3, 9, 4), Math.abs(-7), 2 ** 10);
console.log("A".charCodeAt(0), String.fromCharCode(66));
console.log(Number.isInteger(7.0), Number.isNaN(Number("x")));Syntax
const clean = input.trim().toLowerCase(); // methods can be chained
const words = sentence.split(" ");
const joined = words.join("-");
const shown = total.toFixed(2);
Example
// Strings are read-only: every method gives back a new string.
const title = " learn JavaScript ";
const clean = title.trim();
console.log(clean, clean.length);
console.log(clean.toUpperCase(), clean.indexOf("Java"));
console.log(clean.slice(6), clean.slice(0, 5));
console.log(clean.replace("learn", "teach"), clean.includes("Script"));
const words = "red,green,blue".split(",");
console.log(words, words.join(" + "));Line by line
titlehas spaces at both ends.trimgives a new string without them, andtitleitself is unchanged.- The length is counted, and
indexOffinds"Java"at position 6. slice(6)starts at position 6 and runs to the end.slice(0, 5)stops before position 5.replacechanges the first match, andincludeslooks for a piece of text.split(",")gives a list of three items, andjoinmakes them one string again.
Expected result
learn JavaScript 16
LEARN JAVASCRIPT 6
JavaScript learn
teach JavaScript true
[ 'red', 'green', 'blue' ] red + green + blue
In the real world
Sign-up forms trim and lower-case email addresses so that Mitu@Example.com and mitu@example.com count as the same person. Shops use toFixed to display prices. URL slugs such as learn-java-script are built by replacing spaces with hyphens.
Common mistakes
- Forgetting to keep the result.
name.trim();alone does nothing useful, because strings never change. - Adding
toFixedresults. They are strings, so+joins them. Do the arithmetic first. - Writing
s.length().lengthis a property, so it has no brackets. - Assuming
parseIntis strict.parseInt("12abc")is 12. UseNumberto reject such input.
Best practices
- Clean up input as soon as you read it, with
trimand a consistent case. - Keep numbers as numbers while calculating, and format them only for display.
- Prefer
includesandstartsWithto comparingindexOfresults, because they say what you mean.
Summary
Strings cannot change, so methods give back new ones. slice cuts, split and join move between text and lists, and Math does common calculations. toFixed formats for display, and Number is strict where parseInt is forgiving.
Quick check
Key takeaways
- Strings never change; methods give you a new string.
- split turns text into a list, and join turns a list into text.
- toFixed formats a number for display, and its result is a string.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.