DevPath · Learn to code ESPTEN

Text strings

Methods to transform text

Your toolbox for text

Cleaning up what a user types, uppercasing a name, pulling the domain out of an email... those are all string methods. A method is a function that belongs to a value and is called with a dot: text.method(). Strings come with plenty; here are the ones you'll use every day.

⚠️ CLASSIC TRAP: strings are immutable. A method never changes the original string; it returns a new one. text.toUpperCase() doesn't touch text: it hands you an uppercase copy. If you don't store the result in a variable, you lose it.

Uppercase and lowercase

const text = "Hello World";
console.log(text.toUpperCase()); // "HELLO WORLD"
console.log(text.toLowerCase()); // "hello world"

Searching: includes and indexOf

const phrase = "learn javascript";
console.log(phrase.includes("java")); // true (does it contain "java"?)
console.log(phrase.indexOf("java"));  // 6  (position where it starts)
console.log(phrase.indexOf("python")); // -1 (does not exist)

Slicing: slice

slice(start, end) extracts a part. It includes start but not end:

const word = "JavaScript";
console.log(word.slice(0, 4)); // "Java"
console.log(word.slice(4));    // "Script" (to the end)

Replacing: replace

const greeting = "Hello Pedro";
console.log(greeting.replace("Pedro", "Ana")); // "Hello Ana"

Splitting: split

Turns a string into an array, cutting by a separator:

const csv = "red,green,blue";
console.log(csv.split(",")); // ["red", "green", "blue"]

Cleaning spaces: trim

Removes leftover spaces at the start and end. Your best friend for whatever a user types into a form, which almost always arrives with extra spaces:

const dirty = "   hello   ";
console.log(dirty.trim()); // "hello"

And the best part: since each method returns a string, you can chain them one after another (text.trim().toLowerCase()) and build powerful transformations in a single line.

Examples

Normalize and check

const email = "  USER@Example.COM  ";
const clean = email.trim().toLowerCase();
console.log(clean);
console.log("is gmail?:", clean.includes("gmail"));

Slice and replace

const file = "document.txt";
console.log(file.slice(0, 10));
console.log(file.replace(".txt", ".pdf"));
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Length and access by indexView the module →