Arabic, Hebrew, English, numbers, punctuation, and embedded identifiers can appear to move or align incorrectly when they share a line. This guide explains how Unicode bidirectional text works, how to debug RTL and mixed-direction strings, and how to build safer HTML, CSS, and JavaScript patterns for user-generated content. It also provides a repeatable checklist for localization, forms, tables, filenames, and regression testing.
Overview
Bidirectional text is not necessarily stored in the order that a reader sees it. Unicode characters have directional properties, and the browser applies the Unicode Bidirectional Algorithm (UBA) to determine visual ordering. Arabic and Hebrew generally behave as right-to-left scripts, while Latin letters and many numerals behave as left-to-right. Punctuation, symbols, whitespace, and neutral characters can take their direction from nearby text.
This becomes difficult when a single string contains several directional runs. Consider a support ticket containing an Arabic sentence, an English product name, a version number, and a URL. The underlying string may be correct, yet punctuation can appear beside an unexpected run, a number can seem detached from its label, or a filename can look as though it has been reordered. The visual result depends on the paragraph direction, the direction of each character, and the boundaries around embedded content.
Start by separating three different problems:
- Text direction: the inline ordering of characters and directional runs.
- Layout direction: the flow of blocks, columns, controls, and spacing in the interface.
- Data order: the actual sequence stored, serialized, searched, copied, or transmitted.
Changing CSS may fix layout without fixing text ordering. Adding invisible Unicode controls may change display without changing the underlying data. Debugging is easier when you inspect both the string and its rendering.
For background on code points, character names, and Unicode version differences, see how to find a Unicode character by name or code point and Unicode version compatibility in web apps.
What to track
1. The paragraph or container direction
Set direction at a meaningful structural boundary rather than trying to correct every child element. Use dir='rtl' for a region whose primary reading direction is right-to-left, dir='ltr' for a left-to-right region, and dir='auto' when the direction should be inferred from the first strong directional character.
<article dir='rtl' lang='ar'>
<h1>عنوان المقال</h1>
<p>نص عربي مع اسم المنتج Pro 4.</p>
</article>Prefer the HTML dir attribute for document semantics and inheritance. CSS can reinforce the choice, but direction is not a substitute for correctly marking the language and document structure.
2. Isolation around embedded values
When a user-generated value is inserted into a sentence with a different direction, isolate it. The HTML <bdi> element is designed for this purpose, especially when the value's direction is unknown.
<p>Status for <bdi>{{userName}}</bdi>: <bdi>{{ticketId}}</bdi></p>Use dir='auto' on bdi when the embedded value should determine its own direction:
<bdi dir='auto'>{{displayName}}</bdi>For a known direction, use an ordinary element with an explicit dir value. Isolation prevents the embedded run from influencing the ordering of surrounding text, which is important for names, account numbers, dates, filenames, and labels.
3. Directional controls and isolates
Invisible characters are useful diagnostic clues, but they should be introduced deliberately. The following controls are the ones most likely to appear during debugging or in imported text:
| Control | Code point | Purpose | Guidance |
|---|---|---|---|
| LRM | U+200E | Left-to-right mark | Provides a small LTR directional hint near punctuation or short values. |
| RLM | U+200F | Right-to-left mark | Provides a small RTL directional hint near punctuation or short values. |
| ALM | U+061C | Arabic letter mark | Helps preserve Arabic directional context in specific text sequences. |
| LRI / RLI | U+2066 / U+2067 | Left-to-right or right-to-left isolate | Starts an isolated directional span. |
| FSI | U+2068 | First-strong isolate | Uses the first strong character in the span to determine direction. |
| PDI | U+2069 | Pop directional isolate | Ends an isolate started by LRI, RLI, or FSI. |
| LRE / RLE / PDF | U+202A / U+202B / U+202C | Legacy embedding controls | Inspect carefully; prefer HTML isolation or modern isolate controls for new code. |
Always pair isolate controls correctly, and avoid sprinkling LRM or RLM characters into stored data merely to make one screen look right. If you must use a control, document why, test copy and paste, and decide whether it belongs in presentation data rather than the canonical value.
4. CSS direction and logical properties
Use direction for the inline direction and use logical properties for layout that should adapt between LTR and RTL. For example:
.message {
direction: rtl;
margin-inline-start: 1rem;
padding-inline: 1rem;
border-inline-start: 0.25rem solid currentColor;
text-align: start;
}
.toolbar {
display: flex;
gap: 0.5rem;
justify-content: flex-start;
}margin-inline-start, padding-inline, border-inline-start, and text-align: start express intent without hard-coding left and right. This reduces the number of RTL-specific overrides and helps keep components consistent when a locale changes direction. Test icons separately: an arrow, sort indicator, or navigation glyph may need to mirror, while a brand mark, code symbol, or media-control icon may not.
5. The underlying value and rendering context
Inspect the exact string in developer tools, logs, or a controlled test fixture. Check for leading or trailing whitespace, invisible controls, line breaks, non-breaking spaces, and characters that resemble one another. Compare the value before and after JSON serialization, URL encoding, database storage, and sanitization. A display issue may originate in an import pipeline rather than the browser.
For a reusable test set, include Arabic and Hebrew sentences, Latin text embedded in RTL text, RTL text embedded in an English sentence, decimal numbers, dates, URLs, email addresses, parentheses, quotation marks, hyphens, emojis, and filenames. The Unicode test corpus guide can help structure those fixtures.
Cadence and checkpoints
RTL bugs are easy to reintroduce when a component, translation, font, browser, or data source changes. Treat bidirectional rendering as a recurring quality check rather than a one-time visual fix.
During implementation
- Mark the document or component with the correct language and base direction.
- Wrap unknown user values in
bdi, or use an explicit directional boundary when the value's direction is known. - Replace physical CSS properties with logical equivalents where the layout should support both directions.
- Test keyboard focus, selection, copy and paste, truncation, wrapping, tooltips, tables, and validation messages.
- Inspect the stored value separately from the rendered value.
Before release
Run a small directionality matrix at minimum: an LTR locale, an RTL locale, mixed-script content, long values, empty values, values beginning with punctuation or numbers, and values containing URLs or identifiers. Test both a component's normal state and its error, loading, disabled, and overflow states. Include screenshots only as supporting evidence; assertions about the string and DOM direction are more durable than pixel comparisons alone.
Monthly or quarterly review
On a monthly or quarterly cadence, review recently changed components and localization fixtures. Check whether new fields accept names, labels, filenames, or free text from users in a different direction. Re-run the matrix after browser-engine upgrades, UI framework upgrades, font changes, changes to sanitization or serialization, and additions of new locales. The exact schedule can follow release risk; the important point is to record the last test date and the conditions tested.
How to interpret changes
If the characters appear in the wrong order but the DOM text is correct, first inspect the nearest directional boundary. A missing or inherited dir value is often more likely than corrupt data. If surrounding punctuation moves when a username or identifier changes, add isolation rather than inserting arbitrary marks around the punctuation.
If the whole interface feels mirrored incorrectly, inspect the layout layer: flex alignment, grid placement, margins, borders, transforms, and icons. A component can have correct text direction while still using physical left and right properties that break in RTL.
If only copied, searched, or serialized values are wrong, compare the canonical string at each pipeline boundary. Do not normalize away characters until you know their purpose. Invisible directional controls may be present in imported content, and removing them can either resolve or create a problem depending on the intended context.
Also distinguish direction from language. Set lang for pronunciation, shaping, hyphenation, and accessibility context, and set dir for directional behavior. A string can contain Arabic characters while appearing inside an English paragraph, or it can be Arabic text containing an English product name. Neither language nor direction should be inferred from a font choice alone.
Security deserves a separate check. Directional controls can make identifiers, filenames, source-code snippets, and log lines appear different from their logical order. Treat untrusted text as data, escape it for its output context, and provide a way to inspect or copy the underlying value. Do not rely on visual order when reviewing commands, account details, URLs, or permissions. Unicode directionality is a rendering feature, not an authorization boundary.
For related processing concerns, see the guides to using Unicode safely in HTML, CSS, JavaScript, and JSON and Unicode property escapes in regular expressions.
When to revisit
Revisit this checklist whenever a new RTL locale is added, a form begins accepting a new kind of identifier, or a component starts displaying user-generated text. Schedule a broader review after browser or framework upgrades, changes to fonts and text rendering, modifications to URL or JSON handling, and any report that a name, number, filename, or punctuation mark appears in the wrong place.
Keep a compact regression page in the project with representative fixtures and an explanation of any intentional directional marks. Record the browser and operating-system combinations used for verification, but avoid treating one screenshot as a universal result. Browser behavior and Unicode data can evolve, so verify important cases in the environments your users actually rely on.
When a failure is reported, capture four things before changing code: the exact logical string, its code points or escaped representation, the surrounding HTML and computed direction, and the user-visible context. Then apply the smallest structural fix: establish the correct base direction, isolate the embedded value, use logical CSS, or correct the data pipeline. Re-run the full matrix, including copy and paste, and add the failing example to the test corpus. This turns an intermittent RTL text problem into a repeatable frontend layout test.