Regular vs Non-Breaking Spaces \u00a0

25 August, 2021
2 min read

Today at work I came across a failing test that made me wonder if the previous developer had just given up and left it fail. The failing test looked to be comparing two identical strings but failing at the spaces.

To replicate this issue, you can fire up the NodeJS REPL and follow along.


Each > is a command to be executed in the REPL.

I've highlighted parts to take note of.

➜  ~ node
Welcome to Node.js v16.7.0.
Type ".help" for more information.
> const assert = require('assert')
> const nonBreakingSpace = '\u00a0'
> const space = ' '
> assert.strictEqual(nonBreakingSpace, space);
Uncaught AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

' ' !== ' '

    at REPL4:1:8
    at Script.runInThisContext (node:vm:129:12)
    at REPLServer.defaultEval (node:repl:562:29)
    at bound (node:domain:421:15)
    at REPLServer.runBound [as eval] (node:domain:432:12)
    at REPLServer.onLine (node:repl:889:10)
    at REPLServer.emit (node:events:406:35)
    at REPLServer.emit (node:domain:475:12)
    at REPLServer.Interface._onLine (node:readline:487:10)
    at REPLServer.Interface._line (node:readline:864:8) {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: ' ',
  expected: ' ',
  operator: 'strictEqual'

In HTML,  's are used to prevent two words from breaking or wrapping at the end of a line.

Looking at the log above, it is not immediately obvious what is going on. This is even less obvious when the spaces exist in a sentence, or when the text exists in html as something like:

<!--I had to change the above from &nbsp; because it broke this parser!-->

When this is rendered by a React testing library, the &nbsp; will appear identical to a normal space when rendered.

I had a suspicion it was an issue with ASCII characters only because I remember an old prank regarding replacing semicolons ; with the Greek question mark ;.

I fixed the breaking test by entering the actual ASCII code instead of the copy-pasted space.

For example:

assert.strictEqual(expected, "Don't\u00a0break\u00a0me")