学习库JavaScriptStrings and Numbers

Strings and Numbers

Format text, parse numeric input, round deliberately, and avoid floating-point surprises.

更新于 适用于 ECMAScript 2026

Strings and numbers appear at every system boundary. Normalize them early and format them close to the interface.

Work with text

text.js
const raw = "  JavaScript Course  ";
const title = raw.trim();
console.log(title.toLowerCase().includes("script"));
console.log(title.slice(0, 10));
console.log(`Now learning: ${title}`);

Strings are immutable: methods return new values. Use replaceAll, split, startsWith, and endsWith when they express the transformation clearly.

Parse and format numbers

numbers.js
const minutes = Number("112");
if (!Number.isFinite(minutes)) throw new TypeError("minutes must be numeric");
const hours = Math.floor(minutes / 60);
const remainder = minutes % 60;
console.log(`${hours}h ${remainder}m`);

Binary floating point cannot represent every decimal exactly. Compare calculated decimals with a tolerance, and store money as integer minor units or use a purpose-built decimal type.

Keep this

Trim and validate boundary input, treat strings as immutable, check numeric finiteness, and format for the learner's locale.

学习位置已保存在此设备上。