Module: JavaScript
JavaScriptยท062ยท4 MIN READ

062: Standard Built-ins: String, Number, Math, Date, Intl, and RegExp

TOPICS COVERED: Standard Built-ins: String, Number, Math, Date, Intl, and RegExp

Outcomes

By the end of this lesson, you can:

  • use core built-in objects intentionally;
  • manipulate strings without unnecessary mutation assumptions;
  • validate and format numbers;
  • use Math for numeric utilities;
  • handle dates without confusing display formatting with data storage;
  • format numbers and dates with Intl;
  • create and use regular expressions for suitable text patterns.

Strings

Strings are immutable.

js
const name = "  tea shop  ";

const cleaned = name.trim().toUpperCase();

console.log(cleaned); // "TEA SHOP"
console.log(name);    // original unchanged

Useful methods:

js
"JavaScript".includes("Script");
"JavaScript".startsWith("Java");
"tea,coffee".split(",");
"hello".replace("h", "H");

Use locale-aware behavior when human-language rules matter.

Numbers

js
Number.isFinite(12.5);
Number.isInteger(12);
Number.isNaN(NaN);

Floating-point arithmetic can produce representation artifacts:

js
0.1 + 0.2; // 0.30000000000000004

For money, do not assume binary floating point is exact. Many systems model minor currency units as integers:

js
const unitPricePaise = 1050;
const quantity = 3;
const totalPaise = unitPricePaise * quantity;

Financial systems may require decimal libraries or domain-specific rounding rules. Decide based on the business requirements.

Math

js
Math.round(12.5);
Math.floor(12.9);
Math.ceil(12.1);
Math.max(10, 20, 5);
Math.min(10, 20, 5);
Math.abs(-42);

Random integer in a range:

js
function randomInt(min, max) {
  const lower = Math.ceil(min);
  const upper = Math.floor(max);

  return Math.floor(
    Math.random() * (upper - lower + 1)
  ) + lower;
}

Math.random() is not suitable for cryptographic security. Use crypto.getRandomValues() or platform security APIs for security-sensitive randomness.

Dates

JavaScript Date represents an instant as milliseconds from the Unix epoch, while its APIs also expose calendar fields.

js
const now = new Date();
console.log(now.toISOString());

Parse unambiguous machine timestamps when possible:

js
const createdAt = new Date("2026-08-27T10:30:00Z");

Avoid ambiguous strings such as:

js
new Date("08/09/2026");

Different readers may interpret day/month order differently.

Store versus Display

A good rule:

  • store/transmit a well-defined timestamp or domain date;
  • format it for the user's locale at the UI boundary.
js
const formatter = new Intl.DateTimeFormat("en-IN", {
  dateStyle: "medium",
  timeStyle: "short",
});

console.log(formatter.format(createdAt));

Intl.NumberFormat

Currency:

js
const inr = new Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR",
});

console.log(inr.format(123456.78));

Percent:

js
const percent = new Intl.NumberFormat("en-IN", {
  style: "percent",
  maximumFractionDigits: 1,
});

console.log(percent.format(0.1875));

Prefer Intl over manually inserting commas and currency symbols.

Intl.Collator

Human-friendly sorting:

js
const collator = new Intl.Collator("en", {
  sensitivity: "base",
  numeric: true,
});

const names = ["item 10", "Item 2", "item 1"];

names.sort(collator.compare);

console.log(names);

Regular Expressions

A regular expression describes a text pattern.

js
const codePattern = /^[A-Z]{3}-\d{4}$/;

console.log(codePattern.test("ORD-1024")); // true

Parts:

text
^          start
[A-Z]{3}   three uppercase letters
-          literal hyphen
\d{4}      four digits
$          end

Capturing Data

js
const match = "ORD-1024".match(/^([A-Z]{3})-(\d{4})$/);

if (match) {
  console.log(match[1]); // ORD
  console.log(match[2]); // 1024
}

Named groups:

js
const result = "ORD-1024".match(
  /^(?<prefix>[A-Z]{3})-(?<number>\d{4})$/
);

console.log(result?.groups);

Do Not Use Regex for Everything

Regular expressions are excellent for constrained text patterns. They are poor substitutes for:

  • full HTML parsing;
  • JSON parsing;
  • complex URL parsing;
  • semantic email-address truth;
  • business validation requiring multiple fields.

Use specialized parsers and APIs where they exist.

Worked Example: Receipt Formatter

js
const money = new Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR",
});

const date = new Intl.DateTimeFormat("en-IN", {
  dateStyle: "medium",
  timeStyle: "short",
});

function formatReceipt(order) {
  return [
    `Order: ${order.id}`,
    `Total: ${money.format(order.total)}`,
    `Placed: ${date.format(new Date(order.placedAt))}`,
  ].join("\n");
}

console.log(
  formatReceipt({
    id: "ORD-1024",
    total: 845.5,
    placedAt: "2026-08-27T07:00:00Z",
  })
);

Advanced Notes: Unicode, Time Zones, and Regex State

Strings are Unicode text, but indexing can be surprising

Some Unicode characters use more than one UTF-16 code unit.

js
const emoji = "๐Ÿ˜€";

console.log(emoji.length); // 2
console.log([...emoji].length); // 1 code point

For user-visible text, do not assume .length always equals the number of characters a human perceives. Grapheme clusters can be more complex still.

Intl.Segmenter can help where supported and needed.

Dates and time zones

A timestamp and a calendar date are different domain concepts.

"2026-08-27" may represent a local business date with no time-of-day meaning. Converting it blindly through Date and time zones can shift the visible date.

For business-day, birthday, or schedule-only values, decide explicitly whether the domain represents:

  • an instant;
  • a date;
  • a local date/time;
  • a recurring calendar rule.

Do not make Date choose the business semantics for you.

Stateful regular expressions

Regexes with g or y can maintain lastIndex.

js
const pattern = /\d+/g;

console.log(pattern.test("123")); // true
console.log(pattern.lastIndex);

Reusing stateful regex objects without understanding this can create intermittent-looking bugs.

For validation, anchored non-global regexes are often simpler.

Named capture and replacement

js
const input = "2026-08-27";

const output = input.replace(
  /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/,
  "$<day>/$<month>/$<year>"
);

console.log(output);

Prefer date formatting APIs for real date values; this example demonstrates regex capture mechanics.

Mistakes and Debugging

  • assuming string methods mutate the original string;
  • formatting money with string concatenation only;
  • treating floating-point values as exact decimals;
  • storing locale-formatted dates as machine data;
  • parsing ambiguous date strings;
  • using Math.random() for tokens/passwords;
  • writing a giant regex where multiple validation steps would be clearer.

Exercises

Core

Use Intl.NumberFormat to format INR.

Practice

Validate an order code ABC-1234.

Professional Extension

Write a report formatter that receives ISO timestamps and numeric totals and displays them using a caller-provided locale.

Recap

Built-in objects solve common problems better than hand-written utilities when used with a clear understanding of their semantics and limitations.