JavaScript String Methods
String methods are built-in tools that work on a string and return new text. The original string never changes, because each method builds a fresh string.
Changing case
toUpperCase returns an all-caps copy, and toLowerCase returns an all-lowercase copy. The last line logs the original, and it proves the original stays untouched.
let word = "Hello";
console.log(word.toUpperCase());
console.log(word.toLowerCase());
console.log(word);Cutting and swapping
slice copies the piece between two positions. replace swaps the first match for new text.
let city = "Lisbon";
console.log(city.slice(0, 3));
console.log("red car".replace("red", "blue"));Splitting text
split cuts text at a separator and returns an array. An array is a list value, and the Arrays lessons teach it in full.
let tags = "red,green,blue";
let parts = tags.split(",");
console.log(parts);
console.log(parts.length);Example
let raw = " hello world ";
let clean = raw.trim();
console.log(clean);
console.log(clean.toUpperCase());
console.log(clean.slice(0, 5));
console.log(raw.length);Key points
- A method call returns a new string, and the original string stays as it was.
- Positions in a string count from 0, so the first character sits at position 0.
- The charAt method returns the character at a given position.
- The substring method copies a piece of a string, much like slice does.
- The padStart method pads the start of a string with characters until it reaches a set length.
In this example, trim removes the spaces at both ends of the raw text and stores the result in clean. toUpperCase then returns an all-caps copy of clean, and slice copies its first five characters. The last line prints the length of raw, and its count of 15 proves the original string never changed.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does "hello".toUpperCase() return?