Reputation: 164
I am using template literals for a string in javascript and want to insert special characters like & and $ with hex code (&lettersandnumbers;) like you would in normal strings but it doesn't read it. I tried putting it in ${} but that didn't help either. Is there a way to write it?
Upvotes: 3
Views: 6943
Reputation: 802
The &lettersandnumbers;
escape sequence is for HTML, not JavaScript strings. In javascript strings, there are different ways to represent a special character. In your case, you do not need to escape the character "$" or "&".
To represent a character in a string with a hexadecimal code, do this:`I like \x24\x24\x24!`
which evaluates to "I like $$$!".
Upvotes: 0
Reputation: 943214
See Escape notation on MDN:
Code | Output |
---|---|
\0 | U+0000 NULL character |
' | single quote |
" | double quote |
\ | backslash |
\n | new line |
\r | carriage return |
\v | vertical tab |
\t | tab |
\b | backspace |
\f | form feed |
\uXXXX (where XXXX is 4 hex digits; range of 0x0000–0xFFFF) | UTF-16 code unit / Unicode code point between U+0000 and U+FFFF |
\u{X} ... \u{XXXXXX} (where X…XXXXXX is 1–6 hex digits; range of 0x0–0x10FFFF) | UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF |
\xXX (where XX is 2 hex digits; range of 0x00–0xFF) | ISO-8859-1 character / Unicode code point between U+0000 and U+00FF |
Upvotes: 7
Reputation: 150
You can use escape character (backslash - \) to treat special characters as normal ones.
const text = `text\$somemoretext\&end`;
console.log(text);
Upvotes: 2