The character \
is not "removed from the string". Actually it is part of a escape sequence.
Basically, when you create a string, you have to put its contents in quotes:
var string = 'conteúdo da string';
But what if I want to put the quotes themselves? This doesn’t work here:
var string = 'conteúdo 'da' string'; // errado!
For seeing the '
before da
, Javascript understands that you are actually closing the quotes, and therefore terminating the content of the string. In this case, we need to use the escape sequence \'
to represent the character '
:
var string = 'conteúdo \'da\' string'; // certo
That is, the sequence \'
is interpreted as the character '
, indicating that it is part of the content of the string and should not be treated as the quotes that delimit the string itself. So much so that if you print this string
, the result will be conteúdo 'da' string
.
But then we have another problem: whether the \
is used for escape sequences, as do to represent the character itself \
? Simple, with another escape sequence (in case, it would be \\
):
console.log('can\'t'); // can't
console.log('can\\t'); // can\t
In the code above, \'
is the escape sequence representing the character '
, so the resulting string is can't
. Already \\
is the escape sequence representing the character \
, so the result is can\t
.
If you want the resulting string to be can\'t
, then you’ll have to escape both:
console.log('can\\\'t'); // can\'t
I mean, we have \\
(that represents the character \
) followed by \'
(that represents the character '
), resulting in can\'t
.
Remember also that if you use double quotes ("
) to delimit the string, there is no need to escape the '
(but the \
still need):
// o ' está com escape
console.log("can\'t"); // can't
// mas dentro de aspas duplas, não precisa
console.log("can't"); // can't
// mas o \ precisa
console.log("can\\'t"); // can\'t
Finally, regex has nothing to do with it. Regex would be used if you wanted to detect such characters and/or remove them from the string, for example (still, for simpler cases or need regex). But if it is to generate a string with such characters, just understand how escape sequences work.
See also: Why the expression ``` == '`' is true?