Strings & Template Literals
Strings are the most common data type you'll use in everyday JavaScript. Learn how to create, manipulate, and format text with classic string methods and the powerful ES6 template literal syntax.
What is a String?
A string is a sequence of characters used to represent text. In JavaScript, strings are primitive values wrapped in quotes. They can hold letters, numbers, symbols, whitespace, and Unicode characters — anything you can type.
JavaScript provides three ways to create a string literal:
// All three are valid strings
let a = 'Hello, World!'; // single quotes
let b = "Hello, World!"; // double quotes
let c = `Hello, World!`; // backticks (template literal)
// Mixing quotes to avoid escaping
let msg1 = "It's a great day!"; // double wraps a single quote
let msg2 = 'He said "hello"'; // single wraps double quotes
// Strings are immutable primitive values
typeof a; // → "string"
String Length & Character Access
Every string has a .length property
that returns the number of characters. Individual characters are accessed via
zero-based index using bracket notation or
.charAt().
const str = "JavaScript";
// Length property
console.log(str.length); // → 10
// Character access — zero-based index
console.log(str[0]); // → "J"
console.log(str[4]); // → "S"
console.log(str[str.length - 1]); // → "t"
// .charAt() — equivalent to bracket notation
console.log(str.charAt(0)); // → "J"
// Out-of-range index returns undefined
console.log(str[99]); // → undefined
str[0] = 'x') is silently ignored
in non-strict mode.str.at(-1) returns the last character.
Escape Sequences
When you need to include special characters inside a string that would
otherwise break the syntax, use a backslash \ followed by
an escape code:
| Sequence | Meaning | Example |
|---|---|---|
| \' | Single quote | 'It\'s fine' |
| \" | Double quote | "She said \"hi\"" |
| \\ | Backslash | "C:\\Users\\name" |
| \n | New line | "Line1\nLine2" |
| \t | Tab | "Name\tAge" |
| \r | Carriage return | "line\r\nend" |
| \uXXXX | Unicode character (4 hex) | "\u2764" → ❤ |
| \u{XXXXX} | Extended Unicode (ES6) | "\u{1F600}" → 😀 |
// Escape sequences in practice
const quote = 'She said, \'Hello!\'';
const path = "C:\\Projects\\app.js";
const lines = "First line\nSecond line\nThird line";
const heart = "\u2764 I love JS"; // → "❤ I love JS"
const rocket = "\u{1F680} Launching"; // → "🚀 Launching"
console.log(lines);
// First line
// Second line
// Third line
Essential String Methods
JavaScript's String prototype comes
packed with built-in methods. Because strings are immutable, every method returns a
new string — the original is never changed.
true if the string contains the given
substring, otherwise false.substr, or
-1 if not found.
start up to
(not including) end. Supports negative indices..replaceAll() or a
regex with /g to replace all occurrences..join() on an array to reverse.
count times.
+ operator or
template literals in modern code.null.const str = " Hello, JavaScript World! ";
// Case conversion
str.toUpperCase(); // " HELLO, JAVASCRIPT WORLD! "
str.toLowerCase(); // " hello, javascript world! "
// Trimming whitespace
str.trim(); // "Hello, JavaScript World!"
// Searching
str.includes("JavaScript"); // true
str.startsWith(" H"); // true
str.indexOf("World"); // 22
// Slicing
str.trim().slice(0, 5); // "Hello"
str.trim().slice(-6); // "orld!" — negative counts from end
// Replace
str.replace("JavaScript", "JS"); // " Hello, JS World! "
"a-b-c-d".replaceAll("-", "/"); // "a/b/c/d "
// Split / Join
"one,two,three".split(","); // ["one", "two", "three"]
["one", "two"].join(" & "); // "one & two"
// Padding
"5".padStart(3, "0"); // "005"
// Repeat
"ha".repeat(3); // "hahaha"
String Concatenation
Before template literals, developers used the + operator to join strings together. While it still works,
template literals are now the preferred approach for readability.
const first = "Rahul";
const last = "Sharma";
const age = 28;
// ❌ Old style — concatenation with +
const msg1 = "Hello, " + first + " " + last + ". You are " + age + " years old.";
// ✅ Better — template literal
const msg2 = `Hello, ${first} ${last}. You are ${age} years old.`;
console.log(msg1 === msg2); // true — identical result
// Number + String coercion gotcha
console.log(1 + 2 + " cats"); // "3 cats" ← left-to-right: 1+2=3, then "3"+"cats"
console.log("cats: " + 1 + 2); // "cats: 12" ← string first, so 1 and 2 are coerced
+ operator encounters a string, it switches from addition to
concatenation. Mixing numbers and strings with + can produce
unexpected results. Use Number() or template literals to be explicit.
Template Literals (ES6)
Introduced in ES2015, template literals use backticks
(`) instead of quotes. They unlock three powerful
capabilities: interpolation, multi-line strings, and
tagged templates.
const name = "Priya";
const score = 87;
const max = 100;
// 1. String interpolation — embed any expression
const result = `${name} scored ${score}/${max} (${(score/max*100).toFixed(1)}%)`;
console.log(result); // "Priya scored 87/100 (87.0%)"
// 2. Multi-line strings — line breaks are literal
const html = `
<div class="card">
<h2>${name}</h2>
<p>Score: ${score}</p>
</div>
`;
// 3. Expressions — ternary, function calls, math
const grade = `Grade: ${score >= 90 ? "A" : score >= 75 ? "B" : "C"}`;
console.log(grade); // "Grade: B"
// 4. Nesting template literals
const items = ["HTML", "CSS", "JS"];
const list = `Skills: ${items.map(i => `[${i}]`).join(", ")}`;
console.log(list); // "Skills: [HTML], [CSS], [JS]"
${ } —
variables, arithmetic, ternary operators, function calls, even other template literals. The
expression is evaluated and converted to a string automatically.
Tagged Template Literals
A tagged template allows you to process a template literal with a function. The tag function receives the string parts and interpolated values as separate arguments — enabling sanitization, localization, styled components, and more.
// Tag function signature: (strings, ...values)
function highlight(strings, ...values) {
return strings.reduce((acc, str, i) =>
acc + str + (values[i] !== undefined ? `<strong>${values[i]}</strong>` : ""),
"");
}
const lang = "JavaScript";
const year = 1995;
const output = highlight`${lang} was created in ${year}.`;
console.log(output);
// "<strong>JavaScript</strong> was created in <strong>1995</strong>."
// ─── Real-world: basic HTML sanitizer ───────────────────
function safe(strings, ...values) {
const escape = v => String(v)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
return strings.reduce((acc, str, i) =>
acc + str + (values[i] !== undefined ? escape(values[i]) : ""), "");
}
const userInput = '<script>alert("xss")</script>';
console.log(safe`User said: ${userInput}`);
// "User said: <script>alert("xss")</script>"
${}
placeholders. Always has one more element than values.\n shows as the two characters \ and
n instead of a newline.
Try It — Live Editor
Edit the code below and see the output update in real time. Try modifying the template literal, adding string methods, or experimenting with escape sequences.
Quick Reference — String vs Template Literal
A side-by-side comparison of how to solve common string tasks with the classic syntax vs. the modern template literal approach:
// ── Interpolation ──────────────────────────────────────────
// Before (ES5)
var msg = "Hi " + name + ", you are " + age + ".";
// After (ES6+)
const msg = `Hi ${name}, you are ${age}.`;
// ── Multi-line ──────────────────────────────────────────────
// Before
var html = "<ul>\n" +
" <li>Item 1</li>\n" +
"</ul>";
// After
const html = `
<ul>
<li>Item 1</li>
</ul>
`;
// ── Dynamic HTML building ────────────────────────────────────
const users = ["Alice", "Bob", "Charlie"];
// After (clean & readable)
const listHTML = `
<ul>
${users.map(u => `<li>${u}</li>`).join("\n ")}
</ul>
`;
`"hello"`.toUpperCase() return?- Strings can be created with single quotes, double quotes, or backtick template literals.
- Strings are immutable — string methods always return a new string without modifying the original.
- Use escape sequences like
\n,\t,\\, and\uXXXXto include special characters. - Essential methods include
.trim(),.includes(),.slice(),.replace(), and.split(). - Template literals (ES6) use backticks and
${expression}to embed any JS expression inline. - Template literals also support multi-line strings without needing
\n. - Tagged templates let a function pre-process a template literal — powering styled-components, GraphQL, and HTML sanitizers.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.