Strings

Topic 4 of 5 in Variables & types7 min readBeginnerFree course

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.

JavaScript
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:

JavaScript
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.

JavaScript
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:

JavaScript
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:

JavaScript
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.

The string JavaScript with indexes 0 to 9 above each letter and −10 to −1 below. slice(0, 4) selects J, a, v, a — stopping before index 4. at(−1) reads the last letter, t.

JavaScript
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 there

Useful methods

JavaScript
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 alter title; it returns a new string. Save the result if you need it.

Searching

JavaScript
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('.');       // 12

All 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.

JavaScript
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:

JavaScript
'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

JavaScript
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:

JavaScript
const input = '  Hello World  ';
const tag = input.trim().toLowerCase().replaceAll(' ', '-'); // 'hello-world'

Comparing strings

=== compares strings exactly, including case and spaces.

JavaScript
'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:

JavaScript
'Zebra' < 'apple';  // true  — 'Z' has a lower code than 'a'

For sorting text in human order, use localeCompare, which understands case and accents:

JavaScript
['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:

JavaScript
for (const char of 'hey') {
  console.log(char); // 'h', 'e', 'y'
}

Emoji and some other characters take two “slots”. '😀'.length is 2. for…of and [...text] handle them correctly, while indexing with [i] can split them in half. For user-facing character counts, prefer [...text].length.

Exercise

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'.

JavaScript
function toSlug(title) {
  // your code here
}

function initials(fullName) {
  // your code here
}

Summary

  • Strings are immutable — methods return a new string.
  • Characters are numbered from 0; .length counts them; .at(-1) reads from the end.
  • Template literals use backticks and ${} for values and multi-line text.
  • includes, startsWith, slice, split and replaceAll cover most everyday text work.
  • Use localeCompare to sort text in human order.