In C# you can use verbatim strings like this:
@"\\server\share\file.txt"
Is there something similar in JavaScript?
Strings in JavaScript are a sequential arrangement of Unicode characters, enclosed inside “ ” or ' ' . Both are valid ways to define a string. In JavaScript, a valid string can be: console.
String interpolation in JavaScript is a process in which an expression is inserted or placed in the string. To insert or embed this expression into the string a template literal is used. By using string interpolation in JavaScript, values like variables and mathematical expressions and calculations can also be added.
Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes. Besides, using backticks makes it easier for string operations.
In JavaScript, there are three ways to write a string — they can be written inside single quotes ( ' ' ), double quotes ( " " ), or backticks ( ` ` ).
Template strings do support line breaks.
`so you can do this if you want`
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
It does not of course prevent expansion from occurring the in the text, and by extension, code execution but maybe that's a good thing?
Note: I don't think there's a way to take an existing string and run it through expression interpolation. This makes it impossible to inject code this way since the code has to originate in the source. I don't know of an API that can do expression interpolation on-demand.
Note 2: Template strings are a ES2015 / ES6 feature. Support in every browser except (wait for it...) IE! However, Edge does support template strings.
Note 3: Template strings expand escape sequences, if you have a string inside a string that string will expand its escape sequences.
`"A\nB"`
...will result in:
"A B"
...which will not work with
JSON.parse
because there's now a new-line in the string literal. Might be good to know.
No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes.
I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method.
What I did to solve this was as follows:
public void Alert(string message) { message = message.Replace("\\", "\\\\") .Replace("\r\n", "\n") .Replace("\n", "\\n") .Replace("\t", "\\t") .Replace("\"", "\\\""); // and now register my JavaScript with this safe string. }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With