trimStart And trimEnd Trim One Side Only
trimStart removes leading whitespace, trimEnd removes trailing whitespace, trim does both; repeated calls stay idempotent on trimmed strings.
Code
// trimStart 只修左侧:行首对齐符号保留右侧空隙
const left = ' ready ';
console.log('trimStart :', JSON.stringify(left.trimStart()));
// trimEnd 只修右侧:调用方决定留哪边的空白
console.log('trimEnd :', JSON.stringify(left.trimEnd()));
// trim 两边都去:与 trimStart+trimEnd 等价
console.log('trim :', JSON.stringify(left.trim()));
// 解析固定宽度记录:去空白后再判断是否为空
for (const raw of [' ', ' data ', 'x']) {
const cell = raw.trim();
console.log('cell :', cell === '' ? '(blank)' : cell);
}
// 重复 trim 是幂等的:二次调用返回相同结果
console.log('idempotent :', left.trimStart().trimStart() === left.trimStart());Output
Captured from a sandboxed run of this snippet in the build pipeline.
trimStart : "ready "
trimEnd : " ready"
trim : "ready"
cell : (blank)
cell : data
cell : x
idempotent : trueInside the snippet
The file repeats itself only inside for (const raw of [' ', ' data ', 'x']).
Module-level bindings hold the data — left — with no function scope in between.
Putting it to use
Running the file prints labeled results such as trimStart :, trimEnd :, trim : — each operation’s effect is visible in the output.
Core lines
const left = ' ready ';
const cell = raw.trim();
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Its state lives in module-level bindings: `left`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.