Tutorials JavaScript Strings & Template Literals
Ch 9 / 78
Chapter 9 Beginner 9 min read JavaScript

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 you'll learn
Creating strings with single, double & backtick quotes
Essential string properties and built-in methods
Escape sequences and special characters
ES6 template literals & string interpolation
Multi-line strings and embedded expressions
Tagged templates and advanced use cases

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:

''
Single Quotes
Classic syntax. Can't contain an unescaped single quote inside.
""
Double Quotes
Identical to single quotes. Useful when the string contains apostrophes.
JavaScript
// 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"
Note
Strings in JavaScript are immutable — you cannot change a character in place. String methods always return a new string rather than modifying the original.

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().

JavaScript
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.length
Returns the total number of UTF-16 code units in the string. For most characters, one code unit = one character.
str[index]
Bracket notation — reads-only access to a character at a zero-based position. Writing to it (e.g. str[0] = 'x') is silently ignored in non-strict mode.
str.at(index)
ES2022 method. Supports negative indexing — 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}" → 😀
JavaScript
// 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.

.toUpperCase() / .toLowerCase()
Converts all characters to upper or lowercase.
returns string
.trim() / .trimStart() / .trimEnd()
Removes whitespace from both ends, the start, or the end of a string.
returns string
.includes(substr)
Returns true if the string contains the given substring, otherwise false.
returns boolean
.startsWith(str) / .endsWith(str)
Checks if the string begins or ends with a given substring.
returns boolean
.indexOf(substr)
Returns the first index of substr, or -1 if not found.
returns number
.slice(start, end)
Extracts a portion of the string from start up to (not including) end. Supports negative indices.
returns string
.replace(search, replacement)
Replaces the first match. Use .replaceAll() or a regex with /g to replace all occurrences.
returns string
.split(delimiter)
Splits the string into an array using a delimiter. Use .join() on an array to reverse.
returns array
.padStart(len, char) / .padEnd()
Pads a string to a target length from the start or end. Useful for formatting numbers.
returns string
.repeat(count)
Returns a new string with the original repeated count times.
returns string
.concat(...strs)
Joins two or more strings. Prefer the + operator or template literals in modern code.
returns string
.match(regex)
Matches the string against a regular expression, returning an array of matches or null.
returns array | null
JavaScript — String Methods
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"
⚡
Free Resource
Download our JavaScript Cheat Sheet
All string methods, template literal patterns & ES6+ features — one page.
Get Sheet

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.

JavaScript
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
Watch out
When the + 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.

`Hello, ${name}! You have ${count * 2} messages.`
Backtick delimiters Plain text ${ } placeholder Any JS expression
JavaScript — Template Literals
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]"
Tip
You can embed any valid JavaScript expression inside ${ } — 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.

JavaScript — Tagged Templates
// 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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
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: &lt;script&gt;alert("xss")&lt;/script&gt;"
strings
Array of static string segments between the ${} placeholders. Always has one more element than values.
...values
Rest parameter containing each evaluated expression in order. The tag function can transform, sanitize, or ignore these values.
strings.raw
Property on the strings array that gives the raw (unprocessed) string, where \n shows as the two characters \ and n instead of a newline.
Note
Tagged templates are the foundation of popular libraries like styled-components (CSS-in-JS), graphql-tag, and lit-html. Understanding them unlocks a lot of modern JS ecosystem magic.

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.

Live Editor
✎ Editor
👁 Preview

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:

JavaScript — Before vs After ES6
// ── 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> `;
Quick Check
What does `"hello"`.toUpperCase() return?
Quick Check
Which of these is a valid template literal?
Chapter Summary
  • 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 \uXXXX to 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

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel