# Regex in a template literal: where the backslash goes

> A template literal turns \s into s, so a regex shipped inside one matches nothing and throws nothing. It hid five of our detector rows as unread.

Source: https://mosaicbrowser.com/blog/regex-in-template-literal

## A regex that lost its backslashes inside a template literal

A template literal turns \s into s, so a regex shipped inside one matches nothing and throws nothing. It hid five of our detector rows as unread.

![5: Five detector rows that read nothing, beside a screenshot: the Mosaic sidebar with profiles running, each with its own window](https://mosaicbrowser.com/covers/regex-in-template-literal.webp)

Put a regex inside a JavaScript template literal and every backslash in front of a character that isn't a string escape vanishes. `\s` turns into `s`. `\d` turns into `d`, `\.` into a bare dot, and `\b` into a backspace control character, which is worse. Whatever runs the string later gets a different regex from the one you typed. It still compiles, so you get no error, only a pattern that never matches. Double every backslash (`\\s`) or tag the literal with `String.raw`, and the problem goes away.

We know this the expensive way. It hid five rows of our detection catalogue, and every one of them read as a problem with the site.

## What the page received

`run-detection-tests.mjs` is the script that opens each of our catalogue's detector pages in a profile and reads the verdict off it. A row's probe is a few lines of code that find the verdict text, and the probes live inside template literals in that one file, because they travel to the page as a string. (It is the same runner that once left about 30 tabs open, until [each test got a fresh tab](https://mosaicbrowser.com/blog/one-tab-per-detector).) The BrowserScan bot row had this line, written the way you would write it in a `.js` file:

```
const m = t.match(/Test\s+Results?:?\s*([A-Za-z ]{3,30})/i)

```

Run that line through a template literal in Node and print it, and this is what the page gets:

```
const m = t.match(/Tests+Results?:?s*([A-Za-z ]{3,30})/i)

```

`Tests+` now means "Test followed by one or more letter s". No page on earth prints that. The page in question printed `Test Results: Normal` in plain text, and the probe reported "Headline missing, 4/4 check cards rendered". The row came back `unread`.

`unread` is an honest status in our catalogue. It means the extractor found no verdict, which usually means the site changed its layout or stopped rendering one. So the status sent the next person to look at the site, which had nothing wrong with it.

Mosaic is a desktop app

Email yourself the link and open it on your computer.

[How it works: REST API](https://mosaicbrowser.com/features/rest-api)

## Five rows, and one that was not even JavaScript

Five rows were in that state: `browserscan-bot`, `creepjs-prototype`, `creepjs-workers`, `fingerprint-scan` and `coveryourtracks`. Four were the same eaten `\s`. The `creepjs-prototype` row is the one that reads [CreepJS's prototype page](https://mosaicbrowser.com/blog/creepjs-prototype-page), which names every property a spoof has tampered with, so for as long as it was `unread` we had no reading from one of the most useful pages in the catalogue.

`creepjs-workers` had it worse. Somewhere in its probe sat `'\n'`, quoted with single quotes. Unlike `\s`, `\n` *is* an escape the template literal knows, so it became a real newline, splitting a single-quoted string across two lines. JavaScript won't accept that. The page threw the entire probe away.

What made all five hard to see on review is that the older extractors in the same file had their backslashes doubled correctly. Reading the file, every regex looked like a regex. The difference between `\s` and `\\s` is one character in a line that looks right either way.

Some escapes do fail loudly. Template literals refuse octal-looking escapes, so a backreference such as `\1` is a syntax error in the source file and Node stops on it. That is the lucky case. The quiet escapes are the ones that ship.

## The check that runs every probe the way the page does

`npm run check:extractors` now runs inside our build, and it checks two things because there are two ways to be wrong.

1. A lone `\s`, `\d`, `\b`, `\w`, `\/` or `\.` inside a probe. None of those means anything as a string escape, so each one is always a `\\` that was not typed. This is an exact rule, not a guess.
2. Every probe, evaluated as the page would receive it, is passed to `new Function`. That is the same parse the page does and nothing more, so a probe like the `'\n'` one fails the build instead of failing in a browser.

The checker had three bugs of its own, all found by its `--self-test` mode, which feeds it known faults and known good code:

- It tracked quotes, and the comments in our scripts are prose with apostrophes. `doesn't` opened a "string" that ran to the next apostrophe, and the checker reported eighteen faults against an ordinary line in a different file. Comments are skipped now; ordinary strings are not, because skipping them loses track of where the file is.
- It parsed the source text instead of the string's value. A correct `\\/` in the source is `\/` in the value, but read raw it looked like a regex closing early. A checker that fails the fix it asks for gets switched off.
- It treated literals with `${…}` in them as probes. Those are messages being put together, not scripts sent to a page whole.

## What the rows said once they parsed

With the probes fixed, four of the five rows passed. The fifth, `creepjs-workers`, started reporting that the page and its workers disagreed, and it took three more measurements to turn that into a fact. Two of the mismatches were the extractor's own: it compared fields against the word `unknown` that CreepJS prints for a field a realm lacks, and it compared stack depth, which is smaller in a worker in every browser. With those two removed, 12 disagreements in 57 fields became 3 in 45, all canvas.

A stock Chrome agreed with itself in the page and in all three kinds of worker. Ours did not, and the cause was real: the page's `toBlob` and `convertToBlob` were returning the canvas without its noise, byte-identical to stock, so the canvas defence could be read around by calling a different method. A change in our engine closed it, and the row now reads "3 worker realms agree with the window across 45 fields" (CreepJS's word for a page or a worker is a realm). The extractor had been right once it parsed. We would not have seen any of it while the probe was failing to parse.

Here's why it stung. A broken probe and a site that shows no verdict look identical in our table, yet only the second tells you anything about the site. We had a mirror image of this with a [retired detector that still answers 200](https://mosaicbrowser.com/blog/dead-detector-returns-200). The whole catalogue, 49 rows in five groups, is described in [forty-nine detectors](https://mosaicbrowser.com/blog/forty-nine-detectors).

## How to keep the backslash in a regex inside a template literal

There are three workable habits. Mixing them in one file is how we got here, so choose one:

- Doubling. Write `/Test\\s+Results?/` and the page gets `/Test\s+Results?/`. Ugly, but obvious once everyone does it.
- `String.raw`. The tag keeps what you typed, single backslashes included. You still have to escape a backtick.
- Not putting the regex in a string at all. Ship its `source` and flags as data, or keep the probe as an ordinary function in an ordinary file and send `fn.toString()`.

And whichever one you use, test the string by parsing it. Your editor and TypeScript treat the probe as one opaque string; to them it's text, not code. Nothing reads it as JavaScript until the page does, which is too late to find out.

## Questions

### Why does my regex not work inside a template literal?

The literal handles escapes first. \s, \d and \w mean nothing to a string, so it drops the backslash and the regex gets plain s, d and w. Write two backslashes, or tag the literal with String.raw.

### How do I keep a backslash in a JavaScript template literal?

Type it twice: \\s in your source comes out as \s. String.raw is the other option; that tag skips escape processing, so what you typed is what you get.

### Does the same thing happen with new RegExp and an ordinary string?

Yes. In single quotes '\s' is just s too, and new RegExp('\d+') ends up as d+. Only a regex literal, /\d+/, keeps a lone backslash, since it never passes through string parsing.

### Why did a backreference like \1 throw instead of failing quietly?

Octal-style escapes are banned in template literals, so Node refuses to load the file. Annoying, but you notice. It's \s and \b, which fail without a sound, that make it to production.

## Related

[49 browser fingerprint detectors, and how we read them](https://mosaicbrowser.com/blog/forty-nine-detectors): Our browser fingerprint detectors list: 49 public test pages in five groups, 40 read by a script and 9 kept as reference because they print no verdict.

[What CreepJS's prototype page tells you about JavaScript spoofing](https://mosaicbrowser.com/blog/creepjs-prototype-page): CreepJS's prototype page checks each native function's keys, source and errors. A value faked in JavaScript trips it; one set inside the engine leaves nothing.

[A retired bot test can still answer 200 and look like a pass](https://mosaicbrowser.com/blog/dead-detector-returns-200): Antoine Vastel's fp-scanner demo now serves his homepage with HTTP 200, which a challenge reader scores as a pass. His tests moved; here is where.

[Thirty tabs open: why a test suite needs a fresh tab per site](https://mosaicbrowser.com/blog/one-tab-per-detector): Captcha popups and ad windows left about 30 tabs open in our detector runner. Now each test gets its own tab, and a sweep closes every stray when it ends.









[Commercial bot gates are not test sites](https://mosaicbrowser.com/blog/test-bot-protection-on-website): A live bot gate on someone else's site tells you whether one visit was served. To test bot protection on your own website, read your vendor's logs.

[A fresh browser for every test run, and why it should be cheap](https://mosaicbrowser.com/blog/fresh-profile-per-test-run): Leftover cookies and storage are where flaky browser tests come from. A one-time profile gives each run a clean jar and trashes itself when its browser closes.

## Mosaic, on your own computer

The browser this blog is about: its own Chromium, fingerprints from real machines and a proxy IP per profile. Free covers 3 profiles with no card, and Pro is $25 a month for any number of them.

Mosaic is a desktop app

Email yourself the link and open it on your computer.
