Menu
Coddy logo textTech

String Methods

Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 4 of 65.

Here are some commonly used string methods:

<b>toUpperCase()</b> and <b>toLowerCase()</b>: Convert a string to all uppercase or lowercase.

let str = "Hello";
console.log(str.toUpperCase()); // "HELLO"
console.log(str.toLowerCase()); // "hello"

<b>replace()</b>: Replaces a specified value with another value in a string. It only replaces the first occurrence by default.

To replace all occurrences, you need to use <b>replaceAll()</b>:

let str = "Hello World World";
console.log(str.replace("World", "JavaScript"));
// "Hello JavaScript World"

console.log(str.replaceAll("World", "JavaScript"));
// "Hello JavaScript JavaScript"

trim(): Removes whitespace from both ends of a string.

let str = "  Hello World  ";
console.log(str.trim()); // "Hello World"

charAt(): Returns the character at a specified index in a string.

let str = "Hello";
console.log(str.charAt(1)); // "e"

You can also access a character at a specific index using brackets []:

let str = "Hello";
console.log(str[1]); // "e"
challenge icon

Challenge

Easy

Create a function named alternateCase that takes a string as input and returns a new string where the cases are alternated. The first character should be uppercase, the second lowercase, the third uppercase, and so on.

Cheat sheet

Common string methods in JavaScript:

toUpperCase() and toLowerCase() convert strings to all uppercase or lowercase:

let str = "Hello";
console.log(str.toUpperCase()); // "HELLO"
console.log(str.toLowerCase()); // "hello"

replace() replaces the first occurrence of a value, while replaceAll() replaces all occurrences:

let str = "Hello World World";
console.log(str.replace("World", "JavaScript")); // "Hello JavaScript World"
console.log(str.replaceAll("World", "JavaScript")); // "Hello JavaScript JavaScript"

trim() removes whitespace from both ends of a string:

let str = "  Hello World  ";
console.log(str.trim()); // "Hello World"

charAt() returns the character at a specified index, or use bracket notation:

let str = "Hello";
console.log(str.charAt(1)); // "e"
console.log(str[1]); // "e"

Try it yourself

function alternateCase(str) {
  // Write your code here
}
// Do not write anything outside function
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow