It is a known issue that unknown string escape sequences lose their escaping backslash in JavaScript normal and template string literals:
When a character in a string literal or regular expression literal is
preceded by a backslash, it is interpreted as part of an escape
sequence. For example, the escape sequence \n
in a string literal
corresponds to a single newline character, and not the \
and n
characters. However, not all characters change meaning when used in an
escape sequence. In this case, the backslash just makes the character
appear to mean something else, and the backslash actually has no
effect. For example, the escape sequence \k
in a string literal just
means k
. Such superfluous escape sequences are usually benign, and do
not change the behavior of the program.
In regular string literals, one needs to double the backslash in order to introduce a literal backslash char:
console.log("\s \\s"); // => s \s
console.log('\s \\s'); // => s \s
console.log(`\s \\s`); // => s \s
There is a better idea: use String.raw
:
The static String.raw()
method is a tag function of template
literals. This is similar to the r
prefix in Python, or the @
prefix in C# for string literals. (But it is not identical; see
explanations in this issue.) It's used to get the raw string form
of template strings, that is, substitutions (e.g. ${foo}
) are
processed, but escapes (e.g. \n
) are not.
So, you may simply use String.raw`\s`
to define a \s
text:
console.log(String.raw`s \s \\s`); // => s \s \\s