Use double backslashes when converting strings to regex

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the regex category.

Last Updated: 2024-11-21

The following Regex, built from a string, was not matching at all:

const regex = new RegExp(`${trackingCookieName}=(\w+)`)

The issue was that a single backslash in a string is ignored and removed by the interpreter.

"\w"
=> "w"

"\c\d\e"
=>"cde"

// But note that some special characters don't even print characters when backslashed
"\f"
""
"\n"
"
"

The JavaScript fix is to double backslash

const regex = new RegExp(`${trackingCookieName}=(\\w+)`)

This is true in other languages too - e.g. Ruby has the same behavior.

Lesson

When converting a string to a regex, don't forget to double backslash.