08. Strings
Backtick-quoted strings (`` ` ``) support multi-line text and `${expr}` interpolation.
What you'll learn
- 1Build strings with template literals.
- 2Know the common methods: `split`, `join`, `replace`, `includes`, `trim`.
- 3Understand that strings are immutable.
- 4Use basic regex syntax (literals, flags) for searching and replacing.
- 5Access characters via index and `length`.
Overview
Backtick-quoted strings (`` ` ``) support multi-line text and `${expr}` interpolation.
Core Concepts
1. Template literals
Backtick-quoted strings (`` ` ``) support multi-line text and `${expr}` interpolation.
const name = "Sua";
const greet = `Hi, ${name}!
keep it up today`;Much more readable than using `+` for concatenation.
2. Common methods
Every string method **returns a new string without mutating the original**.
" hi ".trim(); // "hi"
"hello".toUpperCase(); // "HELLO"
"a,b,c".split(","); // ["a","b","c"]
["a","b"].join("-"); // "a-b"
"banana".replace("a", "A"); // "bAnana" (first occurrence only)
"banana".replaceAll("a","A"); // "bAnAnA"
"hello".includes("ll"); // true
"hello".startsWith("he"); // true3. Indexing and length
Use `str[i]` or `str.charAt(i)` to get a single character. For characters whose code point is split across two UTF-16 units (like many emoji), `[...str]` is the safer choice.
"hello".length; // 5
"abc"[1]; // "b"4. Regex basics
A regex literal is `/.../flags`. Common flags: `i` (case-insensitive), `g` (global), `m` (multi-line).
const re = /\d+/g;
"a1b22c333".match(re); // ["1", "22", "333"]
"price 1500".replace(/\d+/, "###"); // "price ###"Examples
| File | What it covers |
|---|---|
| `01_template_literal.js` | Template literals and multi-line strings |
| `02_methods.js` | trim/upper/replace/includes |
| `03_split_join.js` | Array β string conversion |
| `04_regex_intro.js` | Regex matching and replacing |
src/01_template_literal.js
/**
* Template literals
*/
"use strict";
const name = "Jiho";
const score = 92;
const msg = `Name: ${name}
Score: ${score}
Grade: ${score >= 90 ? "A" : "B"}`;
console.log(msg);
src/02_methods.js
/**
* Common string methods
*/
"use strict";
const raw = " Hello, World! ";
console.log("trim =", `[${raw.trim()}]`);
console.log("upper =", raw.trim().toUpperCase());
console.log("replace =", "banana".replace("a", "A"));
console.log("replaceAll =", "banana".replaceAll("a", "A"));
console.log("includes =", "javascript".includes("script"));
console.log("startsWith =", "javascript".startsWith("java"));
src/03_split_join.js
/**
* split and join
*/
"use strict";
const csv = "apple,banana,grape";
const parts = csv.split(",");
console.log("split =", parts);
const joined = parts.join(" / ");
console.log("join =", joined);
const sentence = "I love javascript";
const words = sentence.split(" ");
const reversed = words.reverse().join(" ");
console.log("reversed =", reversed);
src/04_regex_intro.js
/**
* Regex basics
*/
"use strict";
const text = "Order A1234, qty 56, price 7800";
const digits = text.match(/\d+/g);
console.log("digits =", digits);
const masked = text.replace(/\d/g, "*");
console.log("masked =", masked);
const isEmail = /^[\w.-]+@[\w-]+\.[a-z]+$/i;
console.log("email? =", isEmail.test("user@example.com"));
Common Mistakes
- Assuming string methods mutate the original (they don't β strings are immutable).
- Forgetting `replace` only replaces the first occurrence.
- Hitting old octal behavior with `parseInt("08")` β always pass a radix: `parseInt(s, 10)`.
- Comparing with `==` instead of `===` and falling into coercion traps.
- Measuring emoji length with `.length` and getting the wrong number.
FAQ
Q1. What's the difference between `"` and `'`?
None. Follow your project's convention.
Q2. How do I change a single character in a string?
Build a new string. Example: `s.slice(0, i) + ch + s.slice(i+1)`.
Q3. Regex or includes?
Plain substring checks β `includes`. Pattern matching β regex.
Practice
- `homework_01.js` β Count the words in a string.
- `homework_02.js` β Mask the last seven digits of a Korean RRN with `*`.
homework/README.md
## homework_01.js β Write `wordCount(s)` that returns the number of words split by whitespace.
- Ignore consecutive spaces and leading/trailing whitespace.
## homework_02.js β Write `mask(rrn)` that takes a Korean RRN like `"YYMMDD-XXXXXXX"` and replaces the trailing seven digits with `*`.
homework/answer/homework_01.js
/**
* Homework 1: word count
*/
"use strict";
/**
* @param {string} s
* @returns {number}
*/
function wordCount(s) {
const trimmed = s.trim();
if (trimmed === "") return 0;
return trimmed.split(/\s+/).length;
}
console.log(wordCount(" hello world js ")); // 3
console.log(wordCount("")); // 0
homework/answer/homework_02.js
/**
* Homework 2: RRN masking
*/
"use strict";
/**
* @param {string} rrn
* @returns {string}
*/
function mask(rrn) {
return rrn.replace(/-\d{7}$/, "-*******");
}
console.log(mask("000101-1234567")); // 000101-*******
Next Lecture
[09_Destructuring_and_Spread](../09_ꡬ쑰λΆν΄μ_μ€νλ λ/) β Pulling apart and putting together objects and arrays.
All lecture materials and example code are openly available on GitHub.
View on GitHub β