Strings in JavaScript
Introduction
Strings represent text—usernames, messages, URLs, and JSON payloads. JavaScript strings are everywhere in frontends and Node.js services. This chapter covers creating strings, common methods, immutability, and practical patterns you will reuse in forms, logs, and APIs.
Prerequisites
Creating Strings
Use single quotes, double quotes, or template literals (backticks):
// Three ways to write string literals
const lang = "JavaScript";
const motto = 'Learn by building';
const shout = `I love ${lang}!`;
console.log(lang, motto, shout);Choose one quote style per project; escape inner quotes when needed:
// Escape double quote inside double-quoted string
const quote = "She said, \"Let's code.\"";
console.log(quote);String Length and Indexing
Strings are sequences with zero-based indexes:
// Length and character access
const word = "hello";
console.log(word.length);
console.log(word[0]);
console.log(word[word.length - 1]);Warning
Strings are immutable—you cannot change word[0] = "H" in place. Methods return new strings.
Useful String Methods
| Method | Purpose |
|---|---|
includes | Check substring |
startsWith / endsWith | Prefix/suffix test |
indexOf | Find position |
slice | Extract substring |
toLowerCase / toUpperCase | Case change |
trim | Remove surrounding whitespace |
split | Split into array |
replace | Replace matches |
// Practical method examples
const email = " User@Example.COM ";
const cleaned = email.trim().toLowerCase();
console.log(cleaned);
console.log(cleaned.includes("@"));
console.log(cleaned.replace("@example.com", "@mail.example.com"));Concatenation
+ joins strings; template literals are usually clearer for multiple values:
// Plus concatenation
const first = "Ada";
const last = "Lovelace";
const full = first + " " + last;
// Template literal (preferred for readability)
const fullName = `${first} ${last}`;
console.log(fullName);See Template Strings for advanced interpolation.
Searching and Slicing
// slice start (inclusive) and end (exclusive)
const url = "https://example.com/docs";
const path = url.slice(url.indexOf("/docs"));
console.log(path);Splitting and Joining
// CSV-like line to array and back
const line = "java,python,javascript";
const tags = line.split(",");
console.log(tags);
const rebuilt = tags.join(" | ");
console.log(rebuilt);Mini Example: Slugify a Title
// Turn a blog title into a simple URL slug
const title = " Hello, JavaScript World! ";
const slug = title
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "");
console.log(slug);Regex appears in a later chapter—here it keeps the example realistic.
FAQ
Are strings objects?
Primitives behave like objects temporarily when you call methods ("hi".length). Prefer thinking of them as immutable primitives.
How do I compare strings?
Use === for exact match. Case-insensitive compare: normalize with toLowerCase() first.
What about Unicode and emoji?
JavaScript strings are UTF-16. Emoji and some characters may use two code units—Array.from(str) or iterators help for advanced cases.
Single or double quotes?
Team choice. Be consistent; ESLint quotes rule can enforce it.
What comes next?
Template strings, then Numbers.