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-03-02

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"


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

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.


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