String Operations
Learn about string operations
String Operations
What are string operations?
String operations allow you to change strings by adding, removing, re-ordering etc. They let you extract parts of strings, change formatting, search for text, and more.
Benefits of string operations?
- Process user input and game text
- Extract data from strings
- Format messages and output
- Search and replace text
- Validate and parse information
const message = "Welcome to the Game!";
console.log(message.length); // 21
console.log(message.toUpperCase()); // WELCOME TO THE GAME!
console.log(message.toLowerCase()); // welcome to the game!
console.log(message.charAt(0)); // W
console.log(message.indexOf("Game")); // 15
console.log(message.substring(0, 7)); // Welcome
console.log(message.includes("Game")); // true
console.log(message.replace("Game", "Adventure")); // Welcome to the Adventure!
const words = message.split(" ");
console.log(words); // ["Welcome", "to", "the", "Game!"]
const joined = words.join("-");
console.log(joined); // Welcome-to-the-Game!
What does this code do?
- Uses
.lengthto count characters - Uses
.toUpperCase()and.toLowerCase()to change case - Uses
.charAt()to get a specific character - Uses
.indexOf()to find where text starts - Uses
.substring()to extract part of string - Uses
.includes()to search for text - Uses
.replace()to substitute text - Uses
.split()and.join()to break apart and reassemble strings
Try It Yourself
%%js // CODE_RUNNER: string-operations const text = “ sword,shield,potion “; const trimmed = text.trim(); console.log(trimmed); const items = trimmed.split(“,”); console.log(items.length); const joined = items.join(“ | “); console.log(joined);