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.

JavascriptForm Validation

Code

javascriptsnippet
18 lines
// 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 : true

Inside 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

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`.