Spreadsheet imports, CRM exports, and free-text address fields rarely store Brazilian regions consistently. One row contains São Paulo with Portuguese diacritics, the next has espirito santo in lowercase ASCII, a third already stores DF, and a fourth arrives with a typo such as Minas Gerias. Downstream shipping, tax, and reporting tables expect a canonical two-letter Unidade Federativa (UF) code.

Reaching straight for fuzzy string matching looks tempting, yet running a fuzzy matcher before accent-insensitive exact lookup introduces avoidable false positives on short state names. This tutorial uses conversor-estado-para-sigla-uf to build a deterministic-first UF normalizer in Node.js, verify edge cases with assertions, and inspect its browser batch converter.

TL;DR

Clone the repository next to a Node.js project, pin fuse.js@3.2.0 to match the bundle's v3 search contract, and load ./repo/dist/index.js:

mkdir uf-normalizer-demo && cd uf-normalizer-demo git clone https://github.com/paladini/conversor-estado-para-sigla-uf.git repo npm init -y npm install fuse.js@3.2.0 

Run a quick check:

const { Estado, converterEstado, closest } = require("./repo/dist/index.js"); console.log(Estado.SP); // "SÃO PAULO" console.log(converterEstado("sao paulo")); // "SP" console.log(closest("Minas Gerias")); // "MG" 

Check trimmed two-letter codes first, run converterEstado for exact accent-folded matches, and call closest only as a guarded fallback for typos.

Prerequisites

  • Node.js 18 or newer (verified on Node.js 24.15.0) and npm.
  • Git to clone the source repository.
  • Any modern browser to test the static batch page.

Release and packaging facts to know upfront:

  • The project is MIT licensed (LICENSE).
  • Although package.json lists "version": "1.0.0", the repository currently has no Git release tags on master (checked at commit 809a9f6) and is not published on the public npm registry. Treat the repository checkout or vendored dist/index.js file as master-branch source rather than a published registry release.
  • The live static browser converter is hosted at paladini.github.io/conversor-estado-para-sigla-uf.

1. Set up a reproducible workspace

Create a clean folder, clone the repository into repo, and install fuse.js@3.2.0:

mkdir uf-normalizer-demo && cd uf-normalizer-demo git clone https://github.com/paladini/conversor-estado-para-sigla-uf.git repo npm init -y npm install fuse.js@3.2.0 

Two repository details explain this layout:

  1. package.json sets "main": "index.js", which does not exist at the repository root; the compiled UMD bundle is ./repo/dist/index.js.
  2. Production builds in webpack.config.js mark fuse.js as an external dependency, and package-lock.json resolves fuse.js to 3.2.0. Installing fuse.js@3.2.0 in the parent directory satisfies require("fuse.js") when Node.js loads dist/index.js.

2. Build a two-stage UF normalizer

Inspecting src/index.js reveals four named exports:

  • Estado: maps all 27 UF codes (26 states plus DF for DISTRITO FEDERAL) from src/sigla-estado.json to uppercase accented Portuguese names.
  • UF: the inverted table mapping uppercase accented names back to UF codes.
  • converterEstado(needle): strips diacritics and compares uppercase strings, throwing TypeError when no state matches.
  • closest(needle): runs Fuse search and returns the top UF code or undefined.

Create normalize-uf.js to combine those exports safely and report which stage matched:

const assert = require("node:assert/strict"); const { Estado, UF, converterEstado, closest } = require("./repo/dist/index.js"); function resolveUf(rawInput) { if (typeof rawInput !== "string") return { uf: null, method: "invalid-type" }; const cleaned = rawInput.trim(); if (!cleaned) return { uf: null, method: "empty" }; const upper = cleaned.toUpperCase(); if (Object.prototype.hasOwnProperty.call(Estado, upper)) { return { uf: upper, name: Estado[upper], method: "code" }; } try { const exactUf = converterEstado(cleaned); return { uf: exactUf, name: Estado[exactUf], method: "exact-nfd" }; } catch { // converterEstado throws TypeError when Array.prototype.find returns undefined } if (cleaned.length < 4) return { uf: null, method: "too-short-for-fuzzy" }; const fuzzyUf = closest(cleaned); return fuzzyUf ? { uf: fuzzyUf, name: Estado[fuzzyUf], method: "fuzzy-fuse" } : { uf: null, method: "unmatched" }; } const sampleRows = [ "São Paulo", " espirito santo ", "Para", "Paraná", "Minas Gerias", "Santa Catrina", "DF", "Rio", "Unknown Region", ]; for (const row of sampleRows) { console.log(JSON.stringify(row), "->", JSON.stringify(resolveUf(row))); } assert.equal(Object.keys(Estado).length, 27); assert.equal(UF["DISTRITO FEDERAL"], "DF"); assert.equal(resolveUf("Para").uf, "PA"); assert.equal(resolveUf("Para").method, "exact-nfd"); assert.equal(resolveUf("Minas Gerias").uf, "MG"); assert.equal(resolveUf(" espirito santo ").uf, "ES"); assert.equal(resolveUf("DF").uf, "DF"); assert.equal(resolveUf("Rio").uf, null); assert.equal(resolveUf("Unknown Region").uf, null); console.log("All assertions passed."); 

Each check solves a concrete input hazard: trimming avoids whitespace mismatches, checking Estado preserves existing codes (closest("DF") returns undefined), wrapping converterEstado catches unmatched throws, and cleaned.length < 4 blocks ambiguous three-letter prefixes ("Rio") while preserving four-letter state names (Acre and Pará).

3. Expected result and reproducible verification

Execute the script:

node normalize-uf.js 

Verify the output and assertion summary:

"São Paulo" -> {"uf":"SP","name":"SÃO PAULO","method":"exact-nfd"} " espirito santo " -> {"uf":"ES","name":"ESPÍRITO SANTO","method":"exact-nfd"} "Para" -> {"uf":"PA","name":"PARÁ","method":"exact-nfd"} "Paraná" -> {"uf":"PR","name":"PARANÁ","method":"exact-nfd"} "Minas Gerias" -> {"uf":"MG","name":"MINAS GERAIS","method":"fuzzy-fuse"} "Santa Catrina" -> {"uf":"SC","name":"SANTA CATARINA","method":"fuzzy-fuse"} "DF" -> {"uf":"DF","name":"DISTRITO FEDERAL","method":"code"} "Rio" -> {"uf":null,"method":"too-short-for-fuzzy"} "Unknown Region" -> {"uf":null,"method":"unmatched"} All assertions passed. 

Tracking method lets an ingestion pipeline auto-accept "code" and "exact-nfd" matches while flagging "fuzzy-fuse" rows for review.

4. Browser batch conversion

For interactive cleanup, index.html provides two <textarea> columns: #nomes converts one state name per line via conversorEstadoParaSiglaUf.closest, and #siglas maps UF codes back to state names via Estado[s.toUpperCase()]. Because index.html attaches keypress listeners rather than input or paste, press Enter inside the textarea after pasting a column to trigger conversion.

Why it works

src/index.js pairs two distinct string algorithms:

  1. Unicode canonical decomposition (converterEstado): str.normalize("NFD") separates precomposed letters (ã, á, é, í, ô) into base ASCII letters plus combining marks (U+0300 to U+036F). Removing /[\u0300-\u036f]/g and uppercasing maps "São Paulo" and "sao paulo" identically to "SAO PAULO".
  2. Bitap fuzzy matching (closest): Fuse runs over the accented NOMES array with threshold: 0.3, location: 0, and distance: 0, tolerating minor typos near the start of a name ("Minas Gerias" to "MG", "Santa Catrina" to "SC").

Ordering matters because of Pará (PA). closest searches accented strings ("PARÁ", "PARAÍBA", "PARANÁ") without accent folding. Passing unaccented "Para" directly to closest("Para") matches all four ASCII prefix characters of "PARAÍBA" with zero character mismatches and returns "PB" instead of "PA". Calling converterEstado("Para") first folds "PARÁ" to "PARA" and returns "PA".

Failure modes, limitations, and security boundaries

  • Uncaught TypeError on misses: converterEstado indexes .find(...)[1] directly without trimming or null-checking. Passing " São Paulo ", "", or an unknown label throws TypeError. Always trim first and guard with try/catch.
  • Fuse.js v3 lock-in: src/index.js evaluates fuse.search(needle).map(i => UF[NOMES[i]])[0]. In fuse.js v3, searching a string array returns numeric indices; in fuse.js v6+, .search() returns { item, refIndex } objects, making NOMES[i] evaluate to undefined. Pin fuse.js@3.2.0.
  • Ambiguous prefixes: Shared prefixes of four or more letters still resolve to the top-scoring candidate; closest("Mato") returns "MT" even if a truncated row meant Mato Grosso do Sul (MS). Quarantine fuzzy matches when source fields may be truncated.
  • Legacy dev toolchain: devDependencies target Webpack 3 and webpack-dev-server 2.9.7 from 2017, and npm test exits with "Error: no test specified". Consume dist/index.js directly rather than running the legacy dev server on a network.
  • Privacy and CDN boundaries: In Node.js, dist/index.js runs strictly in memory with zero network calls. In index.html, updates write to textarea.value rather than innerHTML, avoiding DOM injection from pasted text; however, fuse.min.js (3.0.4) loads from cdnjs.cloudflare.com without a Subresource Integrity (integrity) hash. Add SRI or self-host the script for restricted deployments.

FAQ

Does the dictionary include Distrito Federal?
Yes. src/sigla-estado.json includes all 26 states plus "DF": "DISTRITO FEDERAL" (27 entries).

Can I map UF codes back to state names?
Yes. Read Estado[code.toUpperCase()] after checking Object.prototype.hasOwnProperty.call(Estado, code.toUpperCase()).

Why not npm install conversor-estado-para-sigla-uf?
The package is not published on npm, and its root package.json "main" points to "index.js" instead of "dist/index.js". Pin a Git commit or vendor dist/index.js with its MIT license notice.

Takeaway

conversor-estado-para-sigla-uf gives JavaScript workflows a compact 27-entry UF dictionary, NFD accent folding, and Fuse.js typo recovery, provided you enforce a clear boundary: pin fuse.js@3.2.0, trim inputs, run converterEstado before closest, and separate exact resolutions from fuzzy matches.

When cleaning regional address columns in ETL pipelines, do you auto-accept low-distance fuzzy matches or route every non-exact match to a review queue?

AI assistance disclosure: AI helped research, structure, and draft this tutorial. Repository files (src/index.js, src/sigla-estado.json, package.json, package-lock.json, webpack.config.js, index.html, LICENSE), npm registry status, the GitHub Pages site, and all Node.js examples were verified locally before publication.