Chapter 11 of 28 · JavaScript for Beginners — Complete Free Tutorial
Strings & Template Literals
Text is everywhere: labels, validation, URLs, messages. JavaScript strings come with a deep toolbox of methods, and template literals let you build dynamic text without clumsy concatenation. This chapter covers the methods worth memorising and the formatting patterns you will reuse constantly.
Creating strings
const a = 'single quotes';
const b = "double quotes"; // identical results
const c = `template literal`; // backticks — interpolation + multi-line
const multi = `Line one
Line two`; // real newlines, no \n needed
console.log(typeof a); // → string
console.log('hi'.length); // → 2
Pick one quote style for your project and stay consistent (most style guides choose single or backticks).
Template literals: ${} interpolation
const name = 'Asha';
const points = 42;
console.log(`${name} scored ${points} points.`);
// → Asha scored 42 points.
console.log(`1 + 1 = ${1 + 1}`); // → 1 + 1 = 2 (any expression)
console.log(`Modulo: ${10 % 3}`); // → Modulo: 1
console.log(`Status: ${score >= 40 ? 'pass' : 'fail'}`);
Anything inside ${ } runs — function calls, ternaries, arithmetic. Nested backticks work too. This replaces chains like 'Hi ' + name + ', you have ' + n + ' msgs'.
Reading and searching
const s = 'JavaScript is fun';
console.log(s.length); // → 17
console.log(s[0]); // → J
console.log(s.at(-1)); // → n
console.log(s.indexOf('is')); // → 5 (or -1)
console.log(s.includes('fun')); // → true
console.log(s.startsWith('Java')); // → true
console.log(s.endsWith('fun')); // → true
console.log(s.search(/is/i)); // → 5 (regex accepted)
Transforming
const msg = ' Hello World ';
console.log(msg.trim()); // → 'Hello World' (also trimStart/trimEnd)
console.log('hello'.toUpperCase()); // → 'HELLO'
console.log('HELLO'.toLowerCase()); // → 'hello'
console.log('hi'.repeat(3)); // → 'hihihi'
console.log('abc'.padStart(10, '.'));// → '.......abc'
console.log('abc'.padEnd(4, '-')); // → 'abc-'
Remember: strings are immutable — every method returns a new string. s.trim() does nothing unless you use the result: const clean = s.trim();.
Slicing and splitting
const file = 'report-2026.pdf';
console.log(file.slice(0, 6)); // → 'report' (start inclusive, end exclusive)
console.log(file.slice(7, 11)); // → '2026'
console.log(file.slice(-4)); // → '.pdf' (from the end)
console.log(file.substring(0, 6)); // → 'report' (similar; negatives not supported)
console.log('a,b,c'.split(',')); // → ['a', 'b', 'c']
console.log('one line\nnext'.split('\n')); // → ['one line', 'next']
console.log(['a', 'b'].join(' - ')); // → 'a - b'
Replacing
console.log('cat dog'.replace('cat', 'bird')); // → 'bird dog' (first match only)
console.log('cat cat'.replaceAll('cat', 'bird')); // → 'bird bird'
console.log('Cat'.replace(/cat/gi, 'dog')); // → 'dog' (regex, case-insensitive)
// Capitalise first letter
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
console.log(cap('keyboard')); // → 'Keyboard'
Accessing characters safely
const s = 'hi';
console.log(s[99]); // → undefined (no error)
console.log(s.charAt(99)); // → '' (empty string)
console.log([...s]); // → ['h', 'i'] — spread iterates real characters
Practical recipes
// Truncate with ellipsis
const truncate = (t, max = 30) => t.length > max ? t.slice(0, max - 1) + '…' : t;
// Initials
const initials = (full) => full.split(' ').map((w) => w[0]).join('.');
console.log(initials('Ada Lovelace')); // → 'A.L.'
// Count occurrences
const count = (s, sub) => s.split(sub).length - 1;
console.log(count('banana', 'an')); // → 2
// slugify for URLs
const slugify = (t) => t.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
console.log(slugify('My First Post!')); // → 'my-first-post'
A quick look at regular expressions
match, replace and search all accept patterns — /pattern/flags:
console.log('Order 42'.match(/\d+/)); // → ['42']
console.log('a-1, b-2'.matchAll(/([a-z])-(\d)/g)); // iterator of matches
console.log(/\s/.test('has space')); // → true
Full coverage — anchors, groups, quantifiers, validation — has its own chapter: Regular Expressions (chapter 26).
Unicode reality check
console.log('👍'.length); // → 2 (UTF-16 code units, not “one emoji”)
console.log([... '👍'].length); // → 1 (spread sees real code points)
For everyday Latin text, .length is character count. For emoji-heavy input, iterate with [...str] or use Intl.Segmenter.
Common mistakes
- Forgetting immutability —
s.replace(...)discarded; assign the result. indexOfvsincludes—indexOfreturns a position or-1; using it inif (s.indexOf(x))fails when the match is at index 0 (falsy!). Useincludes.- Building HTML with concatenation — hard to read and easy to break; template literals + (careful) escaping, or DOM APIs from chapter 15.
- Assuming
replacereplaces all — without/gorreplaceAll, only the first match changes.
Practice checklist
- Write
shout(s)that uppercases and appends'!'using template literals. - Build a word-count function with
trim().split(/\s+/). - Extract the domain from an email string using
slice/indexOf. - Create
formatName(first, last)returning'Last, First'with proper handling of missing parts.
Strings keep data readable — but where do variables live? Next: Scope, Hoisting & Closures.
Frequently Asked Questions
JavaScript is the programming language of the web. It adds behaviour to pages: responding to clicks and input, validating forms, fetching data from APIs, updating the DOM without reloading, and much more. It also runs on servers (Node.js), in desktop and mobile apps, and in build tooling.
They are unrelated languages that share a similar name for historical marketing reasons. Java is a statically-typed compiled language; JavaScript is a dynamically-typed interpreted language designed for the browser. Knowing one does not imply knowledge of the other.
Helpful but not mandatory — HTML gives you the structure JavaScript manipulates and CSS the styling it toggles. If you know basic tags, classes and selectors, you have enough to start; the DOM chapters assume only that much.
Use const by default and let when the value must change. Avoid var entirely in modern code: it is function-scoped instead of block-scoped, hoists differently, and can create accidental globals. This course uses const and let throughout.
The Document Object Model is the browser’s in-memory tree of objects representing your HTML. JavaScript reads and modifies that tree — selecting elements, changing text, adding nodes, attaching event listeners — and the browser re-renders the page to match.
== compares after converting types (so 5 == "5" is true), while === requires the same value AND the same type (5 === "5" is false). Loose equality has famously confusing rules — use === and !== everywhere unless you have a specific reason not to.
JavaScript is single-threaded, so long-running work (timers, fetches, events) is handled by the browser and its callbacks are queued. The event loop moves queued callbacks onto the call stack only when it is empty, with promise callbacks (microtasks) taking priority over timers. It is why asynchronous code never freezes the page.
A Promise is an object representing a future value — pending, fulfilled or rejected — that can be chained and combined (Promise.all). async/await is syntax sugar over promises that lets asynchronous code read top-to-bottom with ordinary try/catch error handling.
Yes. Frameworks are built on exactly these fundamentals — components are functions, state is your variable discipline, effects are events, rendering is DOM work. Developers who learn vanilla first understand what the framework is doing and debug far faster.
Type out the examples instead of copying, build small end-to-end projects (expense tracker, weather app, quiz), handle every UI state (loading, empty, success, error), and revisit fundamentals while reading real code. Consistency beats volume — a little most days outpaces occasional marathons.