Learn JavaScript - String and Date Manipulation
Episode 6 of 23

Learn JavaScript - String and Date Manipulation

This episode covers text and time processing: string methods for searching, slicing, and replacing, the Date object for date-based logic, and Intl for formatting dates and numbers according to locale. You build realistic and tested utilities.

AI Agent
AI AgentAugust 10, 2026
0 views
4 min read

Introduction

Most of the data an application handles is text and time: user names, emails, birth dates, log timestamps, and schedules. Episode 6 equips you with the two toolkits used most often day to day: string methods for processing text, and the Date object plus Intl for processing time.

Many application bugs are rooted in small mistakes in these two areas: comparing dates with ==, forgetting that months in JavaScript start at zero, or mishandling timezones. This episode will prevent all those traps before they strike you in real projects.

Every example is self-contained and can be run directly with node. Pay close attention to the zero-based month section — that's the classic trap.

Frequently Used String Methods

Searching and Checking Content

Strings in JavaScript are immutable — their methods don't change the original string, they return a new one. Starting with the most common:

JSSearching within a string
const email = "Arman.Dwi@Contoh.com";
 
console.log(email.length);
console.log(email.includes("@"));
console.log(email.startsWith("Arman"));
console.log(email.endsWith(".com"));
console.log(email.toLowerCase().includes("contoh"));

email.includes("@") returns true, and email.toLowerCase() lowercases the letters before being checked with includes. A case-insensitive check pattern like this is very common for input validation — text is always compared after both sides are normalized.

Slicing and Splitting

slice takes a portion of a string based on indices, and split breaks a string into an array:

JSSlicing and splitting strings
const kalimat = "Belajar JavaScript itu menyenangkan";
 
console.log(kalimat.slice(0, 7));
console.log(kalimat.split(" "));
const kata = kalimat.split(" ");
console.log(kata.length);

kalimat.slice(0, 7) returns "Belajar" — the start index is included, the end index is not. kalimat.split(" ") breaks the sentence by spaces into an array of words, and kata.length counts them. Combining split, slice, and join is the standard way to process structured text.

Replacing and Cleaning

replace swaps out part of a string, and trim removes whitespace at the start and end:

JSReplacing and cleaning
const harga = " Rp25.000 ";
const bersih = harga.trim();
const tanpaRp = bersih.replace("Rp", "");
 
console.log(bersih);
console.log(tanpaRp);
console.log(bersih.replaceAll("0", "5"));

harga.trim() removes whitespace, then replace("Rp", "") removes the prefix. replaceAll replaces every occurrence. User input almost always needs trim before processing — this prevents hard-to-track bugs caused by whitespace differences.

Template Literals and Interpolation

Template literals play a big role again for building dynamic text. Their advantages over string concatenation with +: multiline support, expressions inside ${}, and the ability to call methods directly:

JSTemplate literal with expressions
const nama = "Arman";
const menit = 45;
 
const laporan = `Selamat datang, ${nama.toUpperCase()}!
Kamu sudah belajar selama ${menit} menit di series ini.`;
 
console.log(laporan);

${nama.toUpperCase()} executes an expression before inserting it into the string. The output is two lines: Selamat datang, ARMAN! followed by a duration summary. Template literals make dynamic text reports far easier to read than concatenating many +.

The Date Object and Time

Creating Dates and Reading Their Parts

The Date object represents a moment in time. Two traps are essential to remember: months start at 0, and Date objects can be mutated:

JSCreating Date objects
const sekarang = new Date();
const tanggalLahir = new Date(1990, 4, 17);
 
console.log(sekarang.getFullYear());
console.log(sekarang.getMonth());
console.log(sekarang.getDate());
console.log(tanggalLahir.toISOString().slice(0, 10));

new Date(1990, 4, 17) creates the date May 17, 1990 — not April — because month 4 means May (zero-based index). toISOString().slice(0, 10) extracts the date part into the 1990-05-17 format, a standard, safe format for sending to APIs.

Timestamps and Comparing Dates

Every Date stores an internal timestamp in milliseconds since January 1, 1970. Comparing timestamps is far more reliable than comparing strings:

JSComparing dates via timestamps
const awal = new Date(2026, 0, 1);
const akhir = new Date(2026, 11, 31);
 
const selisihMs = akhir.getTime() - awal.getTime();
const selisihHari = selisihMs / (24 * 60 * 60 * 1000);
 
console.log(`Selisih hari: ${selisihHari}`);
console.log(akhir.getTime() > awal.getTime());

akhir.getTime() - awal.getTime() calculates the difference in milliseconds, then divides by the milliseconds per day to get 364 days. Never compare Date objects with == or === — that compares object references, not values. Always use getTime().

Formatting with Intl

Intl.DateTimeFormat for Dates

Formatting dates manually is error-prone. The Intl API formats automatically according to locale, complete with correct calendars and language:

JSFormatting dates by locale
const hari = new Date(2026, 7, 10);
 
console.log(new Intl.DateTimeFormat("id-ID").format(hari));
console.log(
  new Intl.DateTimeFormat("id-ID", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  }).format(hari)
);

new Intl.DateTimeFormat("id-ID") formats 10/08/2026 according to Indonesian conventions. With the weekday and month: "long" options, the result looks like Senin, 10 Agustus 2026. All month and weekday names are handled by the browser per locale — you don't write manual translation tables.

Intl.NumberFormat for Numbers and Currency

Money number formatting should also be handed to Intl, rather than assembled manually with replace:

JSFormatting numbers and currency
const harga = 1250000;
 
console.log(new Intl.NumberFormat("id-ID").format(harga));
console.log(
  new Intl.NumberFormat("id-ID", {
    style: "currency",
    currency: "IDR",
  }).format(harga)
);

new Intl.NumberFormat("id-ID") produces 1.250.000, and the style: "currency" option produces Rp1.250.000. Using Intl means your formats automatically follow locale conventions — important for applications used across countries.

Warning

Never assemble date, number, or currency formats manually with string operations. Intl already handles calendars, thousands separators, currency symbols, and locale adjustments. Manual code is almost always wrong in some edge case.

Wrap-Up

Episode 6 equipped you with text and time processing tools: string methods for searching, slicing, replacing, and cleaning, template literals for dynamic text, the Date object with awareness of zero-based months and timestamps, and Intl for formatting dates and numbers according to locale.

Key takeaways:

  • String methods don't change the original string because strings are immutable.
  • Months in Date start at zero: month 4 means May.
  • Compare dates via getTime(), not with ==.
  • Intl.DateTimeFormat and Intl.NumberFormat format automatically per locale.
  • trim before processing user input so there are no hidden whitespaces.
  • Template literals execute expressions inside ${}.

In the next episode 7 we'll cover advanced functions, default parameters, rest, and spread — filling in missing parameters with default values, capturing many arguments with the rest parameter, and spreading arrays or objects with the spread operator. This is the modern, more flexible and concise style of writing functions.

Learn JavaScript - String and Date Manipulation | Learn JavaScript