Skip to content

JavaScript strings, numbers, dates and regex

Most data that reaches a program is text, numbers and timestamps: a product name typed by a user, a price from a database, an order date from an API. This page covers the built-in tools for each: string methods, numbers and the Math object, the Date object together with Intl for formatting, and regular expressions for matching patterns in text. It also points out where these tools are known to be awkward, such as floating-point rounding and time zones, so you can avoid the classic bugs.

The samples follow an invented shop called OrdersPortal. Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The outputs shown were produced with Node.js 22.23 and the environment variable TZ=UTC; the date sample prints different local times in other time zones, which is part of the lesson.

Topic What you learn
Strings Quotes and template literals, searching, slicing, splitting, padding and immutability.
Numbers and Math Floating point, rounding, parsing, Math methods, random integers and currency formatting.
Dates Creating Date values, UTC versus local time, date arithmetic and Intl.DateTimeFormat.
Regular expressions Literals and flags, test, match, matchAll, replace and named groups.

A string is an immutable sequence of UTF-16 code units. You can write one with single quotes, double quotes or backticks; backticks create a template literal (ES2015) that can span lines and embed expressions with ${...}. Strings cannot be changed in place: every method returns a new string, so you must use the result.

The methods you will use most:

  • Search: includes, startsWith, endsWith (all ES2015, returning booleans) and indexOf (returns -1 when not found).
  • Extract: slice(start, end) (negative indexes count from the end) and at(-1) for the last character.
  • Transform: trim, toLowerCase, toUpperCase, replace (first match) and replaceAll (ES2021), padStart/padEnd (ES2017) and repeat.
  • Split and join: split(",") turns a string into an array; array.join(", ") goes back.

For comparisons that ignore case, normalize both sides first (a.toLowerCase() === b.toLowerCase()), and for sorting human-readable text use a.localeCompare(b), which respects language rules.

const raw = " Ceramic Mug, blue ; GIFT ";
const name = raw.trim();
console.log(`"${name}"`, name.length);
const [product, ...tags] = name.split(/\s*[,;]\s*/);
console.log(product, tags);
console.log(product.toUpperCase(), product.includes("Mug"), product.startsWith("cer"));
const sku = "mug-01";
const label = `${sku.toUpperCase()} | ${product.padEnd(14, ".")} | ${String(7).padStart(3, "0")}`;
console.log(label);
console.log(name.slice(0, 7), name.slice(-4), name.at(-1), name.indexOf("teapot"));
console.log("a-b-c".replace("-", "/"), "a-b-c".replaceAll("-", "/"));
const word = "order";
const changed = word.toUpperCase();
console.log(word, changed); // the original is unchanged
console.log(["Zoë", "anna", "Émile"].sort(), ["Zoë", "anna", "Émile"].sort((a, b) => a.localeCompare(b)));

Output:

"Ceramic Mug, blue ; GIFT" 24
Ceramic Mug [ 'blue', 'GIFT' ]
CERAMIC MUG true false
MUG-01 | Ceramic Mug... | 007
Ceramic GIFT T -1
a/b-c a/b/c
order ORDER
[ 'Zoë', 'anna', 'Émile' ] [ 'anna', 'Émile', 'Zoë' ]

Pitfalls:

  • Ignoring the return value. name.trim(); alone does nothing useful; write name = name.trim().
  • replace with a string changes only the first match. Use replaceAll or a regular expression with the g flag.
  • length counts UTF-16 code units. An emoji such as “🎁” has length 2. Use [...text].length to count code points.

JavaScript has one main numeric type, number: a 64-bit IEEE 754 floating-point value used for both integers and decimals. Integers are exact up to Number.MAX_SAFE_INTEGER (2^53 - 1); beyond that, use bigint. Decimal fractions such as 0.1 cannot be stored exactly, so 0.1 + 0.2 is 0.30000000000000004. For money, store whole cents as integers and format at the end.

Parsing: Number(text) converts the whole string or returns NaN; parseInt(text, 10) and parseFloat(text) read a leading number and ignore the rest. Number.isInteger and Number.isFinite check results without coercion.

The Math object is a namespace of constants and functions, never instantiated: Math.round, Math.floor, Math.ceil, Math.trunc, Math.abs, Math.min/Math.max, Math.sqrt and Math.random(), which returns a float in the range 0 (inclusive) to 1 (exclusive). Note that Math.round rounds halves up toward positive infinity, so Math.round(-2.5) is -2. toFixed(2) returns a string and is subject to the same binary rounding issues.

For display, Intl.NumberFormat formats currency, percentages and thousands separators for a given locale.

console.log(0.1 + 0.2, 0.1 + 0.2 === 0.3);
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
const pricesInCents = [1999, 450, 1];
const totalCents = pricesInCents.reduce((sum, cents) => sum + cents, 0);
console.log("total cents:", totalCents);
const eur = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
console.log(eur.format(totalCents / 100), "|", usd.format(1234567.891));
console.log(Math.round(2.5), Math.round(-2.5), Math.floor(-2.5), Math.trunc(-2.5), Math.ceil(2.1));
console.log((1.005).toFixed(2), typeof (1.005).toFixed(2)); // 1.005 is stored as 1.00499...
console.log(Number("42"), Number("42kg"), parseInt("42kg", 10), parseFloat("3.5 stars"));
console.log(Math.max(...pricesInCents), Math.min(...pricesInCents));
console.log(Number.MAX_SAFE_INTEGER, 2 ** 53 + 1, 2n ** 53n + 1n);
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min; // both ends inclusive
}
const rolls = Array.from({ length: 1000 }, () => randomInt(1, 6));
console.log("min roll:", Math.min(...rolls), "max roll:", Math.max(...rolls));

Output:

0.30000000000000004 false
true
total cents: 2450
24,50 € | $1,234,567.89
3 -2 -3 -2 3
1.00 string
42 NaN 42 3.5
1999 1
9007199254740991 9007199254740992 9007199254740993n
min roll: 1 max roll: 6

Pitfalls:

  • Summing money as decimals. Rounding errors accumulate. Use integer cents and format with Intl.NumberFormat.
  • toFixed returns a string. (2.5).toFixed(2) + 1 is "2.501". Convert back with Number() if you need a number.
  • Using Math.random() for security. It is not cryptographically secure. Use crypto.getRandomValues() or crypto.randomUUID() for tokens and IDs.

A Date object stores one moment in time as the number of milliseconds since 1 January 1970 UTC. It has no time zone of its own; methods like getHours() show that moment in the local time zone of the machine running the code, and getUTCHours() shows it in UTC.

Ways to create a Date:

  • new Date() is now; Date.now() returns now as a number.
  • new Date(2026, 10, 2, 9, 30) uses local time and zero-based months (10 is November).
  • new Date("2026-11-02T09:30:00Z") parses an ISO 8601 string. A date-only string such as "2026-11-02" is treated as UTC midnight, while a date-time without an offset such as "2026-11-02T09:30" is treated as local time.

Date objects are mutable: setDate(getDate() + 7) changes the object, so copy first with new Date(date). Subtracting two dates gives milliseconds. For display, use Intl.DateTimeFormat or toLocaleString with an explicit timeZone, and use toISOString() (always UTC) when sending dates to an API.

Date is known to be awkward. Temporal, a new date and time API with separate types for dates, times and zoned date-times, has finished standardization (Stage 4) and is part of ECMAScript 2027 according to the TC39 finished-proposals list. Node.js 22 does not include it, so this page uses Date and Intl.

const placed = new Date("2026-11-02T09:30:00Z");
console.log(placed.toISOString(), placed.getTime());
console.log("UTC hour:", placed.getUTCHours(), "| local hour (TZ=UTC here):", placed.getHours());
const dateOnly = new Date("2026-11-02");
console.log("date-only string is UTC midnight:", dateOnly.toISOString());
const fromParts = new Date(2026, 10, 2); // month 10 = November, local time
console.log("month index:", fromParts.getMonth(), "->", fromParts.toDateString());
const due = new Date(placed); // copy before changing
due.setUTCDate(due.getUTCDate() + 30);
console.log("due:", due.toISOString().slice(0, 10), "| placed unchanged:", placed.toISOString().slice(0, 10));
console.log("days between:", (due - placed) / (24 * 60 * 60 * 1000));
for (const timeZone of ["Europe/Lisbon", "America/New_York", "Asia/Tokyo"]) {
const text = new Intl.DateTimeFormat("en-GB", { dateStyle: "medium", timeStyle: "short", timeZone }).format(placed);
console.log(timeZone.padEnd(16), text);
}
console.log("invalid:", new Date("02/31/2026 25:00").getTime(), "| Temporal in Node 22:", typeof globalThis.Temporal);

Output:

2026-11-02T09:30:00.000Z 1793611800000
UTC hour: 9 | local hour (TZ=UTC here): 9
date-only string is UTC midnight: 2026-11-02T00:00:00.000Z
month index: 10 -> Mon Nov 02 2026
due: 2026-12-02 | placed unchanged: 2026-11-02
days between: 30
Europe/Lisbon 2 Nov 2026, 09:30
America/New_York 2 Nov 2026, 04:30
Asia/Tokyo 2 Nov 2026, 18:30
invalid: NaN | Temporal in Node 22: undefined

Pitfalls:

  • Zero-based months. new Date(2026, 11, 1) is 1 December. Prefer ISO strings with an explicit offset.
  • Date-only strings shift by a day. new Date("2026-11-02") is UTC midnight, which is 1 November in New York. Keep calendar dates as "YYYY-MM-DD" strings when no time is involved.
  • Invalid dates do not throw. They produce Invalid Date whose getTime() is NaN. Check Number.isNaN(date.getTime()).

A regular expression describes a text pattern. Write it as a literal /pattern/flags, or with new RegExp(text, flags) when the pattern is built at run time. Common syntax: \d (digit), \w (letter, digit or underscore), \s (whitespace), . (any character except line breaks), [A-Z] (a range), + (one or more), * (zero or more), {2,4} (a count), ^ and $ (start and end), (...) (a capture group) and (?<name>...) (a named group, ES2018).

Flags change behavior: g finds all matches, i ignores case, m makes ^ and $ match at line breaks, u enables full Unicode mode and v (ES2024) adds set operations to character classes.

The main methods:

  • regex.test(text) returns true or false.
  • text.match(regex) returns the first match with its groups, or, with g, an array of all matched strings without groups.
  • text.matchAll(regex) (ES2020, requires g) returns every match with its groups.
  • text.replace(regex, replacement) can use $1 or $<name> in the replacement, or a function.

Keep patterns readable and anchored with ^...$ when validating whole values, and prefer simple checks over one giant regex.

const orderId = /^[A-Z]-\d{4}$/;
for (const id of ["A-1001", "a-1001", "A-10010"]) {
console.log(id, orderId.test(id));
}
const note = "Ship A-1001 and A-1002 today; A-1003 waits for stock.";
console.log(note.match(/[A-Z]-\d{4}/));
console.log(note.match(/[A-Z]-\d{4}/g));
const skuPattern = /(?<family>[A-Z]{3})-(?<number>\d{2})/g;
for (const match of "MUG-01 x2, TEE-03 x1".matchAll(skuPattern)) {
console.log(match.index, match.groups.family, match.groups.number);
}
console.log("2026-11-02".replace(/(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/, "$<d>/$<m>/$<y>"));
console.log("Too many spaces".replace(/\s+/g, " "));
console.log("price: 12 EUR, shipping: 3 EUR".replace(/\d+/g, (n) => String(Number(n) * 100)));
const global = /A-\d{4}/g;
console.log("reused g regex:", global.test("A-1001"), global.test("A-1001"), global.lastIndex);

Output:

A-1001 true
a-1001 false
A-10010 false
[
'A-1001',
index: 5,
input: 'Ship A-1001 and A-1002 today; A-1003 waits for stock.',
groups: undefined
]
[ 'A-1001', 'A-1002', 'A-1003' ]
0 MUG 01
11 TEE 03
02/11/2026
Too many spaces
price: 1200 EUR, shipping: 300 EUR
reused g regex: true false 0

Pitfalls:

  • test with the g flag remembers lastIndex. Reusing a global regex alternates between true and false. Drop g for test, or create the regex per call.
  • Unanchored validation. /\d{4}/.test("abc12345") is true. Anchor whole-value checks with ^ and $.
  • Building patterns from user input. Characters such as ., * and ( are special. Escape them before passing text to new RegExp, or avoid regex for plain substring checks with includes.
Need Use
Build text with values Template literals
Check for a substring includes, startsWith, endsWith
Match a pattern or extract parts Regular expression with named groups
Money arithmetic Integer cents, then Intl.NumberFormat
Store or send a moment in time toISOString() (UTC)
Show a date to a user Intl.DateTimeFormat with an explicit timeZone
A calendar date without time A "YYYY-MM-DD" string

1. Why are strings immutable, and what does that mean in practice? String values can never change; methods such as trim or replace return new strings. You must assign the result, and assigning to str[0] silently does nothing (or throws in strict mode).

2. Why is 0.1 + 0.2 !== 0.3, and how do you handle money? Numbers are binary floating point and cannot represent most decimal fractions exactly. Store money as integer minor units (cents), round deliberately, and format with Intl.NumberFormat.

3. What is the difference between new Date("2026-11-02") and new Date("2026-11-02T00:00")? The date-only form is parsed as UTC midnight; the date-time form without an offset is parsed as local midnight. In time zones west of UTC the first one displays as the previous day.

4. What does the g flag change? match returns all matched strings instead of the first match with groups, replace replaces every match, matchAll requires it, and test/exec start from and update lastIndex.

5. Senior scenario: customers in the Americas report that delivery dates shown in the order history are one day early, while European customers see the correct day. The API returns "deliveryDate": "2026-11-20" and the UI shows new Date(value).toLocaleDateString(). What is wrong and how do you fix it? The date-only string is parsed as UTC midnight, and toLocaleDateString shows it in the browser’s zone, which is still the previous evening west of UTC. A delivery date is a calendar date, not a moment: keep it as a string and format its parts directly, or format with timeZone: "UTC". Longer term, model calendar dates as such in the API contract (and with Temporal.PlainDate once the runtimes you target support it).