Concept 5 of 13 Beginner ⏱️ 15 min

Strings

Master working with text data—from basic string operations to powerful manipulation techniques.

Strings are how we work with text in programming. Every username, message, email, and piece of text you see on websites and apps is a string!

What is a String?

A string is a sequence of characters—letters, numbers, symbols, and spaces—wrapped in quotes. Think of it as a "string of characters" all connected together.

let message = "Hello, World!";
let username = "alex_coder";
let emoji = "🎉";
let mixed = "Order #12345";
📝

Strings vs Numbers

"42" (with quotes) is a string—it's text that happens to look like a number. 42 (without quotes) is an actual number you can do math with!

Creating Strings

In JavaScript, you can create strings with three types of quotes:

// Double quotes (most common)
let greeting = "Hello!";

// Single quotes (works the same)
let name = 'Alice';

// Backticks (template literals - special features!)
let message = `Welcome, ${name}!`;

Template Literals

Backticks (`) create template literals, which have special powers:

let name = "Alex";
let age = 25;

// Embed variables with ${}
let intro = `My name is ${name} and I'm ${age} years old.`;
console.log(intro);  // "My name is Alex and I'm 25 years old."

// Multi-line strings
let poem = `Roses are red,
Violets are blue,
Coding is awesome,
And so are you!`;
console.log(poem);

Try It Yourself

String Length

Every string has a .length property that tells you how many characters it contains:

let word = "JavaScript";
console.log(word.length);  // 10

let empty = "";
console.log(empty.length);  // 0

let withSpaces = "Hello World";
console.log(withSpaces.length);  // 11 (space counts!)

Combining Strings

You can join strings together using the + operator. This is called concatenation:

let firstName = "John";
let lastName = "Doe";

// Concatenation
let fullName = firstName + " " + lastName;
console.log(fullName);  // "John Doe"

// Or use template literals
let fullName2 = `${firstName} ${lastName}`;
console.log(fullName2);  // "John Doe"

Essential String Methods

Strings come with many useful methods (built-in functions):

Changing Case

let text = "Hello World";

text.toUpperCase();  // "HELLO WORLD"
text.toLowerCase();  // "hello world"

Trimming Whitespace

let messy = "   extra spaces   ";

messy.trim();       // "extra spaces"
messy.trimStart();  // "extra spaces   "
messy.trimEnd();    // "   extra spaces"

Finding and Checking

let sentence = "The quick brown fox jumps";

// Check if it contains something
sentence.includes("quick");     // true
sentence.includes("slow");      // false

// Check start and end
sentence.startsWith("The");     // true
sentence.endsWith("jumps");     // true

// Find position (index)
sentence.indexOf("quick");      // 4
sentence.indexOf("slow");       // -1 (not found)

Extracting Parts

let text = "JavaScript";

// Get a portion (slice)
text.slice(0, 4);     // "Java"
text.slice(4);        // "Script"
text.slice(-6);       // "Script" (from end)

// Get a single character
text.charAt(0);       // "J"
text[0];              // "J" (also works)

Replacing Text

let greeting = "Hello, World!";

greeting.replace("World", "JavaScript");  // "Hello, JavaScript!"
greeting.replaceAll("l", "L");            // "HeLLo, WorLd!"

Splitting and Joining

// Split a string into an array
let csv = "apple,banana,cherry";
let fruits = csv.split(",");  // ["apple", "banana", "cherry"]

// Join an array into a string
let words = ["Hello", "World"];
let sentence = words.join(" ");  // "Hello World"
⚠️

Strings Are Immutable

String methods don't change the original string—they return a new string. You need to save the result if you want to keep it:

let name = "alice";
name.toUpperCase();      // Returns "ALICE" but doesn't save it
console.log(name);       // Still "alice"!

name = name.toUpperCase();  // Save it back
console.log(name);          // Now it's "ALICE"

Special Characters

Some characters need special codes (escape sequences) to include in strings:

// Newline
let twoLines = "First line\nSecond line";

// Tab
let tabbed = "Name:\tAlice";

// Quotes inside strings
let quote = "She said \"Hello!\"";
let quote2 = 'It\'s a nice day';

// Backslash
let path = "C:\\Users\\Documents";

Common String Tasks

Validate Email (Simple)
function hasAtSign(email) {
  return email.includes("@");
}
Capitalize First Letter
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
Count Words
function countWords(str) {
  return str.trim().split(" ").length;
}

Quick Quiz

Key Takeaways

  • Strings are sequences of characters wrapped in quotes
  • Use template literals (backticks) for embedding variables and multi-line strings
  • .length tells you how many characters a string has
  • Use + or template literals to combine strings
  • Strings have many useful methods: toUpperCase(), slice(), includes(), etc.
  • String methods return new strings—they don't modify the original

What's Next?

Now that you can work with text, let's learn about input and output—how to get information from users and display results!

Finished this concept?

Mark it complete to track your progress