Episode 25 of 46

JavaScript Strings

Learn how to create and manipulate strings in JavaScript.

Strings are sequences of characters used to represent text. They are one of the most commonly used data types.

Creating Strings

let single = 'Hello';
let double = "Hello";
let backtick = `Hello`;  // Template literal

// All three create a string
console.log(typeof single);  // "string"

Template Literals

let name = "Alice";
let age = 25;

// Old way — concatenation
let msg1 = "My name is " + name + " and I'm " + age;

// Modern way — template literals
let msg2 = `My name is ${name} and I'm ${age}`;

// Multi-line strings
let multiLine = `
    This is line 1
    This is line 2
    This is line 3
`;

String Properties and Methods

let str = "Hello, World!";

str.length;              // 13
str.toUpperCase();       // "HELLO, WORLD!"
str.toLowerCase();       // "hello, world!"
str.trim();              // Remove whitespace from both ends
str.indexOf("World");    // 7 (position of first match)
str.includes("Hello");   // true
str.startsWith("Hello"); // true
str.endsWith("!");       // true
str.replace("World", "JavaScript"); // "Hello, JavaScript!"
str.charAt(0);           // "H"
str[0];                  // "H" (bracket notation)

String Immutability

let str = "Hello";
str[0] = "h";         // Doesn't work — strings are immutable
console.log(str);      // "Hello" (unchanged)

// Create a new string instead
let newStr = "h" + str.slice(1);
console.log(newStr);   // "hello"