The fastest way to correct an incorrect character in JavaScript is to isolate where it enters your data, then replace it with the right value and re-validate the output. If the wrong character is a real glyph, like a curly quote, a full-width digit, or a stray zero-width space, the fix usually means normalizing strings with Unicode calls such as normalize("NFKC") plus targeted regular-expression replacements. If it is a garbled byte sequence, like é where é belongs, you are looking at an encoding problem, and replacing characters in code will not fix it. You have to repair the decode or encode step instead. Those two cases look similar on screen but need different solutions. This guide walks through telling them apart, correcting each, and checking that the repair actually held. This guide stays with stable language and platform behavior, without inventing current library versions; anything version-specific should be checked in your own runtime.

Why "incorrect character" describes two different bugs

Before touching code, decide which category you are dealing with, because the cures are not interchangeable.

Category 1: a valid Unicode character you did not want. The string decodes cleanly, but the characters are wrong for your purpose. Examples include a “smart” apostrophe (U+2019) where your parser expects ASCII ', a non-breaking space (U+00A0) breaking a numeric parse, a full-width digit 4 (U+FF14) from a Japanese keyboard, an em dash in a slug, or an invisible zero-width space (U+200B) from copied web text. Each character is legitimate Unicode; the problem is context.

Category 2: mojibake, or mis-decoded bytes. The text arrived as bytes and was decoded with the wrong character encoding. UTF-8 é is the two bytes 0xC3 0xA9; decoded as Latin-1/Windows-1252, those bytes become é. Similarly, UTF-8 ’ becomes ’. This is a data-pipeline bug, not a text-content bug. JavaScript string replacement can cosmetically patch common pairs, but that is fragile; the real repair is fixing the encoding boundary where the mistake happened.

A quick diagnostic: log the code points of the suspect characters.

If instead you see 63 61 66 c3 a9 e2 80 99 73 passed through Latin-1 steps producing é and ’ in the visible string, you are in mojibake territory. Bytes are never wrong in isolation; the label attached to them is.

There is a third, narrower case: the character is correct but displays wrongly, for example as a replacement character � (U+FFFD) or an empty box in a font that lacks the glyph. U+FFFD specifically means a decoder gave up. Finding it in data tells you bytes were invalid or truncated somewhere upstream.

Step-by-step: correcting a wrong character you can see

This procedure assumes the string decodes cleanly and you know which character should be there.

Prerequisite: a reproducible sample of the failing string, and a runtime you can inspect, such as Node.js, a browser console, or your test suite. Knowing the intended character and its code point ahead of time makes each check below decisive.

1: Capture the actual characters, not the rendering. Copy the string from source data into a debugger or console.log([...str]). Rendered text lies: two visually identical spaces can be U+0020 and U+00A0. 2: Identify the code point. Use str.codePointAt(index) or spread the string and map over code points as above. Write down the hex value of the offender and of the intended replacement. 3: Repair with a precise replacement. For a single known offender, str.replaceAll(String.fromCharCode(0x2019), "'") is explicit and readable. Prefer escaping via code points over typing the “smart” character directly into source, so editors and diffs cannot silently convert it. 4: For whole classes of offenders, use Unicode normalization. str.normalize("NFKC") maps full-width forms to ASCII equivalents (4 to 4, full-width letters to normal letters) and folds many compatibility variants. Note that NFKC is a compatibility transformation: it can change characters you wanted, such as some ligatures or superscript digits, so test on representative inputs before applying it to everything. 5: Strip invisible characters explicitly. Zero-width space (U+200B), zero-width no-break space (U+FEFF, often a leftover byte-order mark), and soft hyphen (U+00AD) survive trimming in surprising places because trim() only removes whitespace per the language spec. Replace them by code point or via a targeted regular expression like /[\u200B\uFEFF\u00AD]/g. 6: Re-run the failing code path and assert on the repaired string, not on its appearance. A test that compares code-point arrays catches silent regressions that a visual check misses. 7: Check success with a round trip. If the corrected value flows to storage or an API, read it back and inspect code points again. Expect the same values; if new characters appeared, another boundary in the pipeline is transforming text.

If the intended character was never in the data, replacement cannot invent it. For example, if an upstream system already dropped a diacritic, cafe cannot be turned back into café reliably. The correct fix belongs at the system that lost the information.

Correcting mojibake by repairing the encoding boundary

Mojibake is corrected by undoing the wrong decode, not by substituting characters. The principle: bytes were interpreted under encoding A but were authored in encoding B. Recover the original byte sequence by encoding the visible string under A, then decode those bytes under B.

A classic illustration, runnable in any modern JavaScript environment with TextDecoder:

Success looks like readable text matching the source. Failure shows � where the byte sequence is not valid UTF-8, which means the wrong-decode pair was misidentified or the data was truncated mid-character. Do not iterate blindly through encodings hoping one works; identify both ends of the bad boundary: where the bytes entered (file read, HTTP response, database driver, CSV import) and what encoding was declared there.

Practical checks at each boundary:

Files and streams: read with an explicit encoding such as utf8 rather than relying on defaults, and confirm the file really is UTF-8 by inspecting for a byte-order mark or running a validator. HTTP: the Content-Type charset and the actual bytes must agree. A server declaring text/html; charset=ISO-8859-1 while serving UTF-8 produces textbook mojibake in the browser. Databases and CSV: verify the connection charset and the import tool's assumed encoding. Spreadsheet programs are a common culprit when exporting accented text. TextDecoder and TextEncoder: these work on byte buffers and are the right tools at boundaries; TextEncoder always emits UTF-8, which is worth knowing when interoperating with legacy systems.

Repairing mojibake in place, by mapping known pairs like é to é, works for a handful of documented cases but breaks on mixed content and cannot handle characters whose byte sequences collide with other text. Treat it as a stopgap with a test suite, not a strategy.

Replacement and normalization techniques that hold up

A few JavaScript specifics cause most of the quiet failures in this work.

replace with a global regular expression replaces all matches; replaceAll needs a literal or a global regex. str.replace("’", "'") fixes only the first occurrence, a frequent bug when strings contain several quotes.

Regular expressions operate on UTF-16 code units unless the u flag is set. Characters outside the Basic Multilingual Plane, such as many emoji, are two code units. Without /u, patterns and quantifiers can split them. Use /gu for global replacements on general text:

Normalization forms differ. NFC composes characters (common for storage and comparison); NFD decomposes them (useful when stripping diacritics, for example str.normalize("NFD").replace(/\p{M}/gu, "")). This matters when two strings look identical but compare unequal because one uses é as U+00E9 and the other as e plus U+0301. If equality checks are failing mysteriously, compare normalized forms before concluding the characters are “wrong.”

Avoid regexes that depend on invisible characters typed into the pattern. Always escape by code point (\u2019) so the pattern cannot be corrupted by the same pipeline that corrupted your data.

Watch for confusables. Latin а (Cyrillic U+0430) versus Latin a (U+0061), or Greek ο versus Latin o, appear identical and cause authentication, search, and deduplication bugs. There is no simple normalization that merges scripts; flag suspects by checking whether a string's characters all fall in expected Unicode script ranges, or by maintaining an explicit allowlist for identifiers.

Where incorrect characters come from, and how to prevent them

Corrections are cheaper when you remove the source. The usual entry points:

Copy-paste from word processors and websites inject typographic quotes, en and em dashes, non-breaking spaces, and zero-width characters. Normalize at input, before validation and storage. A single intake function that runs NFKC normalization, converts designated punctuation to ASCII, strips invisible characters, and validates against an allowlist handles most of it:

Apply NFKC only after confirming it does not damage legitimate content such as quantities written with superscripts or characters from scripts where compatibility forms are meaningful. For user-facing display of names and prose, aggressive normalization is risky; validate instead, or normalize only the categories you have decided to accept.

Encoding mismatches at files, HTTP, databases, and CSV imports are prevented by declaring UTF-8 everywhere and testing with non-ASCII fixtures, such as a string containing é, ß, 日本語, and an emoji, that passes through every boundary in an automated test.

Truncation mid-character produces U+FFFD. Multi-byte characters split across buffer boundaries or column-length limits cause it. Validate that stored values contain no U+FFFD and size text columns in characters, not bytes, where the database allows it.

Concatenation and templating bugs can insert the wrong literal, such as a lookalike dash from a design spec. Code review with visible whitespace and a diff tool that flags non-ASCII characters catches these early.

Checks that confirm the fix and catch regressions

Verification should compare semantic values, not screenshots. A compact set that pays for itself:

Code-point assertions: test that a known input produces an exact code-point sequence, so a stray non-breaking space fails the test even though it renders like a normal space. Normalized equality: compare a.normalize("NFC") === b.normalize("NFC") when the requirement is human equivalence rather than byte identity. Round-trip tests through every boundary: write to storage or serialize to an API and read back; assert code points are unchanged or as intended. Fixture-based encoding tests: include a string with accented Latin, CJK, and an astral-plane emoji in test data that crosses each I/O path. Scan for U+FFFD and invisible characters in data validation, and fail loudly rather than storing the damage.

A useful worked estimate: if you maintain, say, 40 strings of test fixtures per input boundary and 5 boundaries, 200 assertions run in milliseconds and would have caught most of the character bugs described here before release.

When the repair needs to go deeper than your own code, such as a vendor API that mangles text or a legacy database that cannot store UTF-8, the fix is architectural. Document the lossy step, convert at the earliest controlled point, and add a monitoring check on output. Stop patching individual characters once the offenders keep changing; that pattern means the boundary, not the text, is broken.