localeCompare Orders Strings Per Locale

Sort user-facing text with String.prototype.localeCompare or Intl.Collator, whose numeric and case-first options fix the classic 2-before-10 ordering bug.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
const files = ["img10.png", "img2.png", "img1.png"];

// 默认字典序:字典序把 "10" 排在 "2" 前
console.log([...files].sort());

// numeric: true 按数值比较内嵌数字
console.log([...files].sort((a, b) => a.localeCompare(b, undefined, { numeric: true })));

// Intl.Collator 复用比较器,批量排序更快
const coll = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
console.log([...files].sort((a, b) => coll.compare(a, b)));

// sensitivity 控制大小写/变音符号是否影响排序
const ci = new Intl.Collator("en", { sensitivity: "accent" });
console.log("cafe" < "café" ? "accent sorts" : "base equal",
  ci.compare("cafe", "café"));

// localeCompare 返回 -1/0/1 形态,可直接做比较器
const names = ["Zoe", "adam", "Åke"];
console.log([...names].sort((a, b) => a.localeCompare(b, "sv")));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

[ 'img1.png', 'img10.png', 'img2.png' ]
[ 'img1.png', 'img2.png', 'img10.png' ]
[ 'img1.png', 'img2.png', 'img10.png' ]
accent sorts -1
[ 'adam', 'Zoe', 'Åke' ]

How it works

Top-level bindings files, coll, ci, names hold the demo state — nothing sits inside a function scope.

What to watch for

  • The environment needs no preparation beyond having the interpreter or compiler.

Putting it to use

The run prints cafe — each prefix names the step that produced it.

Core lines

const coll = new Intl.Collator("en", { numeric: true, sensitivity: "base" });
const ci = new Intl.Collator("en", { sensitivity: "accent" });

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `files`, `coll`, `ci`.