JavaScript + Node.js track

Lesson 08 · Part 2: Objects & Arrays

Strings

Template literals, string methods and an introduction to regular expressions

Part 2: Objects & Arrays2 min readFree lesson

Level: Intermediate | Player: 07_Arrangement_Basics

Learning Objectives

  • Strings can be assembled using template literals.
  • Know frequently used methods such as split, join, replace, includes, and trim.
  • Understand that strings are immutable.
  • Know the basic grammar of regular expressions (literals, flags) and be able to use To-search/replace.
  • Access characters with index and length.

1. Template literal

Supports backticks (`), you can wrap it with a line break and${expr} interpolation.

const name = "Sua";
const greet = `Hello, ${name}!
Fighting today too’;

It has much better readability than + for string concatenation.

2. Frequently used methods

All string methods return a new string without replacing 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" (only the first)
"banana".replaceAll("a","A"); // "bAnAnA"
"hello".includes("ll");       // true
"hello".startsWith("he");     // true

3. Indexing and length

Access a single character with str[i] or str.charAt(i). However, for characters with code points consisting of 2 units, such as emojis, [...str] decomposition is safe.

"hello".length; // 5
"abc"[1];       // "b"

4. Regular expression basics

Regular expression literals are in the part/.../flags format, and i (case-insensitive), g (global), and m (multi-line) are used.

const re = /\d+/g;
"a1b22c333".match(re); // ["1", "22", "333"]
"price 1500".replace(/\d+/, "###"); // "price ###"

Core example

file Contents covered
01_template_literal.js Template literals and multilines
02_methods.js trim/upper/replace/includes
03_split_join.js Array ↔ String conversion
04_regex_intro.js Regular Expression Matching/Substituting Basics

⚠️ Common Mistakes

  1. There is a misunderstanding that the method changes the original. (immutable)
  2. Use replace without knowing that it only changes the first part.
  3. Past octal issue with parseInt("08") — Always specify the decimal number as parseInt(s, 10).
  4. You fall into a type conversion trap when comparing with == rather than ===.
  5. The emoji length is incorrectly measured as length.

❓ Frequently Asked Questions (FAQ)

Q1. What is the difference between " and '? A. They are the same. Follow project conventions.

Q2. How to change one character in a string? A. You must create a new string. Example: s.slice(0, i) + ch + s.slice(i+1).

Q3. Regular expression vs includes? A. includes is suitable for simple inclusion, and regular expression is suitable for pattern matching.

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_template_literal.jsJavaScript
/**
 *template literal
 */
"use strict";

const name = "Jiho";
const score = 92;

const msg = `name: ${name}
Score: ${score}
Rating: ${score >= 90 ? "A" : "B"}`;

console.log(msg);
src/02_methods.jsJavaScript
/**
 *Frequently used 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.jsJavaScript
/**
 *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.jsJavaScript
/**
 *Regular expression basics
 */
"use strict";

const text = "Order number A1234, quantity 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("[email protected]"));

Assignment

homework_01.js

Write wordCount(s) which takes a string and returns the number of words based on white space.

  • Consecutive spaces or spaces at both ends are ignored.

homework_02.js

In the resident registration number format "YYMMDD-XXXXXXX", write mask(rrn), covering the last 7 digits with *.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01.jsJavaScript
/**
 *Task 1: Counting Words
 */
"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_02.jsJavaScript
/**
 *Task 2: Masking resident registration number
 */
"use strict";

/**
 * @param {string} rrn
 * @returns {string}
 */
function mask(rrn) {
  return rrn.replace(/-\d{7}$/, "-*******");
}

console.log(mask("000101-1234567")); // 000101-*******

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now