What’s the use of the [\b] backspace regex?

While all the others are right in general (that \b is a word boundary), \b does mean backspace inside character classes:

[\b]

This will indeed match a backspace character. It’s just an ASCII control character that can appear in text (ASCII code 8, or 10 in octal). I suppose it’s mostly used for legacy reasons, to add diacritical marks (e.g. you could do a, backspace, ´, to get á). Today these have been mostly replaced by Unicode combining marks.

How a string containing a backspace will ultimately look depends on the software that renders it. Consoles will probably still move the cursor back and overwrite what was there if the backspace is followed by new other characters. To see this, fire up an interactive scripting console (like node.js if you want to try it in JavaScript), and run

> console.log("abc\b\bdef")
adef

Note that, had you omitted def, you’d just get abc, because the backspace itself does not erase anything. It only moves the cursor back.

On the other hand, your browser might just ignore it in an input field. For instance, check out a Unicode converter, enter the JavaScript input abc\b\bdef in the bottom left input, hit “convert”, and the “Characters” output will not have the bc erased.

By the way \b being a backspace in character classes is not unique to JavaScript, but interpreted this way in most regex flavors.

Further reading:

Leave a Comment