As I mentioned in my earlier comment, you are dealing with two different escape sequences here:
\n
is an escape sequence for the newline character, i.e. Unicode Character 'LINE FEED (LF)' (U+000A)
\\
is an escape sequence for the backslash, i.e. Unicode Character 'REVERSE SOLIDUS' (U+005C)
Although these escape sequences are two characters in source code, they actually only represent one character in memory.
Observe:
const toEscaped = s => s.toSource().match(/"(.*)"/)[0];
['\n', '\\n', '\\\n', '\\\\n', '\\\\\n']
.forEach(s => console.log(`There are ${s.length} character(s) in ${toEscaped(s)}`))
This also applies in regular expressions. The \n
actually counts as one character so the lookahead (?=.{2})
will attempt to capture the preceding \
as well, which is why you're perhaps seeing some strangeness in the way your replacement works.
However, based on reading some of your comments, it sounds like you might be dealing with incorrect encodings. For example, you may have some cases where a user enters foo\nbar
in an input field, which is interpreted as a literal \
followed by n
(i.e. "foo\\nbar"
) and now you want to interpret this as a newline character, (i.e. "foo\nbar"
). In that case, you're not actually trying to remove \
characters, you're trying to convert the character sequence \
+ n
to \n
.
The following code snippet shows how to perform the escape sequence substitutions for \\
and \n
:
const toEscaped = s => s.toSource().match(/"(.*)"/)[0];
const toHex = s => Array.from(s).map((_, i) => s.charCodeAt(i).toString(16).padStart(2, '0')).join('+');
['\n', '\\n', '\\\n', '\\\\n', '\\\\\n']
.map(s => ({ a: s, b: s.replace(/\\n/g, '\n').replace(/\\\\/g, '\\') }))
.forEach(({a, b}) => console.log(`${toEscaped(a)} --> ${toHex(b)}`))
And to both replace the "\\n"
with "\n"
and remove "\\"
characters preceding it try something like this:
const toEscaped = s => s.toSource().match(/"(.*)"/)[0];
const toHex = s => Array.from(s).map((_, i) => s.charCodeAt(i).toString(16).padStart(2, '0')).join('+');
['\n', '\\n', '\\\n', '\\\\n', '\\\\\n']
.map(s => ({ a: s, b: s.replace(/\\+[n\n]/g, '\n') }))
.forEach(({a, b}) => console.log(`${toEscaped(a)} --> ${toHex(b)}`))
\n
is an escape sequence for the newline character.\\
is an escape sequence for the backslash character. So\\n
is a backslash followed by ann
, and\\\n
is a backslash followed by a newline, and so on.\\
or even better\\+
to empty string and this will only remove one or more occurrence of literal\
and it won't touch your newlines at all if indeed they are newlines and not literal backslash followed by literaln