Strings
Overview
A string is a piece of text — a name, a message, a URL, a whole HTML page. You can write it with single quotes, double quotes or backticks.
const a = 'single';
const b = "double";
const c = `backticks`;Single and double quotes behave identically; pick one and be consistent (this course uses single quotes). Backticks have extra powers, described below.
Quotes inside strings
To put a quote character inside a string, use the other kind of quote around it, or escape it with a backslash:
const a = "It's easy";
const b = 'She said "hi"';
const c = 'It\'s easy';Backslash also starts other special characters:
| Escape | Meaning |
|---|---|
\n |
New line |
\t |
Tab |
\\ |
A literal backslash |
\' \" |
A quote |
é |
A Unicode character (é) |
Template literals
Backticks create template literals. They can hold values with ${} and span several lines.
const name = 'Asha';
const lessons = 3;
const message = `Hi ${name}, you have ${lessons} lessons left.`;
const poem = `Line one
Line two`;Anything inside ${ } is a full JavaScript expression — maths, function calls, even a condition:
const total = `Total: ₹${(price * qty).toFixed(2)}`;
const label = `${count} item${count === 1 ? '' : 's'}`;Before template literals, strings were joined with +. You’ll still see it often:
const greeting = 'Hi ' + name + ', you have ' + lessons + ' lessons left.';Template literals are easier to read and harder to get wrong (no missing spaces), so prefer them.
Positions and length
Each character in a string has a numbered position called an index. Counting starts at 0, so the last character is at length - 1.
const word = 'JavaScript';
word.length; // 10
word[0]; // 'J'
word[word.length - 1]; // 't'
word.at(-1); // 't' — negative numbers count from the end
word[99]; // undefined — no error, just nothing thereUseful methods
const title = ' Learn JavaScript ';
title.length; // 20
title.trim(); // 'Learn JavaScript'
title.toUpperCase(); // ' LEARN JAVASCRIPT '
title.includes('Java'); // true
title.trim().startsWith('L'); // true
title.trim().slice(0, 5); // 'Learn'
'a,b,c'.split(','); // ['a', 'b', 'c']
'ha'.repeat(3); // 'hahaha'
'5'.padStart(3, '0'); // '005'Strings never change.
title.trim()doesn’t altertitle; it returns a new string. Save the result if you need it.
Searching
const email = 'asha@example.com';
email.includes('@'); // true
email.startsWith('asha'); // true
email.endsWith('.com'); // true
email.indexOf('@'); // 4 — position of the first match
email.indexOf('#'); // -1 — not found
email.lastIndexOf('.'); // 12All of these are case-sensitive: 'Hello'.includes('hello') is false. Lower-case both sides first when case shouldn’t matter.
Cutting out parts
slice(start, end) copies the characters from start up to — but not including — end. Leave out end to go to the finish; use negative numbers to count from the end.
const file = 'report-2026.pdf';
file.slice(0, 6); // 'report'
file.slice(7, 11); // '2026'
file.slice(-3); // 'pdf'
file.slice(file.indexOf('.') + 1); // 'pdf'You may also see substring, which is similar but doesn’t accept negative numbers. slice is the one to remember.
Splitting and joining
split turns a string into an array; the array method join turns it back:
'red green blue'.split(' '); // ['red', 'green', 'blue']
'2026-12-03'.split('-'); // ['2026', '12', '03']
'hello'.split(''); // ['h', 'e', 'l', 'l', 'o']
['red', 'green', 'blue'].join(', '); // 'red, green, blue'Replacing
const text = 'cats and cats';
text.replace('cats', 'dogs'); // 'dogs and cats' — first match only
text.replaceAll('cats', 'dogs'); // 'dogs and dogs'For pattern-based replacements (any digit, any whitespace…) you’ll use regular expressions — see Regular expressions.
Chaining methods
Because each method returns a new string, you can chain them, reading left to right:
const input = ' Hello World ';
const tag = input.trim().toLowerCase().replaceAll(' ', '-'); // 'hello-world'Comparing strings
=== compares strings exactly, including case and spaces.
'apple' === 'apple'; // true
'Apple' === 'apple'; // false
'Apple'.toLowerCase() === 'apple'; // true< and > compare strings character by character using their Unicode code numbers. That puts all capital letters before lower-case ones, which is rarely what people expect:
'Zebra' < 'apple'; // true — 'Z' has a lower code than 'a'For sorting text in human order, use localeCompare, which understands case and accents:
['banana', 'Apple', 'cherry'].sort((a, b) => a.localeCompare(b));
// ['Apple', 'banana', 'cherry']Looping over characters
A for…of loop goes through a string one character at a time:
for (const char of 'hey') {
console.log(char); // 'h', 'e', 'y'
}Emoji and some other characters take two “slots”.
'😀'.lengthis2.for…ofand[...text]handle them correctly, while indexing with[i]can split them in half. For user-facing character counts, prefer[...text].length.
Make a slug
Write toSlug(title) that trims a title, lower-cases it and replaces spaces with dashes: toSlug(' Arrow Functions ') → 'arrow-functions'. Bonus: also make initials('Asha Rao') return 'AR'.
function toSlug(title) {
// your code here
}
function initials(fullName) {
// your code here
}function toSlug(title) {
return title.trim().toLowerCase().replaceAll(' ', '-');
}
function initials(fullName) {
return fullName
.split(' ')
.map((part) => part[0].toUpperCase())
.join('');
}Summary
- Strings are immutable — methods return a new string.
- Characters are numbered from 0;
.lengthcounts them;.at(-1)reads from the end. - Template literals use backticks and
${}for values and multi-line text. includes,startsWith,slice,splitandreplaceAllcover most everyday text work.- Use
localeCompareto sort text in human order.