I am trying to assign a HTML block to a string variable in JavaScript. However enclosing quotation/speech marks aren't doing the trick. Is there another way to do this.
This is what I have tried:
var huge = '<div class="row"><div class.../div>'
I've realised I could put / before the quotation marks. However given the size of the block that doesn't seem like a great solution.
EDIT: Sorry, wasn't very clear. I meant that within the block of html code there are multiple sets of double quotes/single quotes which clash with the enclosing single quotes.
If your problem is you have a huge block of code consisting of both single quotes and double quotes, your options are to either escape it server-side first, or you'll have to manually format it.
var huge = "<div class=\"foo\">bar</div>";
Try putting the code in your HTML, rather than in your javascript, but hiding it with CSS. You can then either access it as a DOM element or use .html() to get it as a string.
Related
I'm sorry, I know the issue was addressed before, but I can't make any answer fit my problem...
I am writing a short script on google script, where I want to use the searchFile method on a folder, to look for a file whose name is stored in the string variable Name:
var theFileImLookingFor = theSourceFolder.searchFiles("title = '"+Name+"'").next();
This code works fine as long as the variable Name doesn't include quotation marks. Then, I'm stuck...
Please help me adapt my code :)
A simple but fragile solution could be to use backticks (`), usually found on the upper left of the keyboard on the same key as the tilde (~). These are sort of like quotation marks in javascript, but can also be used in ways that quotation marks can't.
Expect this solution to fail whenever the variable's value contains backticks.
Did you try to escape possible quotes ?
You probably could write a little function that take your variable "name" then escape possible quotes in it before returning it to searchFile. Or maybe with a simple "replace("'", "\'")"...
In the following scenario:
var evil_string = "...";
$('#mytextarea').val(evil_string);
Do I have to escape an untrusted string before using it as the value of a textarea element?
I understand that I will have to handle the string with care if I want to do anything with it later on, but is the act of putting the string in a textarea without escaping inherently dangerous?
I have done some basic testing and the usual special characters &'"< seem to be successfully added to the textarea without interpretation.
No, you don't need to do that. When you assign directly to property of DOM element (which jQuery's .val does under the hood), the data is interpreted verbatim. You only need to quote text with methods that explicitly treat input as HTML - i.e. outer/innerHTML and like.
Putting unescaped strings as values of textboxes or textareas is fine. You only need to worry about it when you are putting strings in your HTML that could potentially be interpreted as other HTML. Generally speaking, this means you should escape the strings when the text could be a child of some HTML DOM Element. This could be done on the server (as lolka_bolka suggested), or on the client before adding the potentially dangerous string to the DOM.
I am writing JavaScript templates for a content management system where users fill out text input fields that are passed to my templates.
My problem is the quotation marks in the input fields are not escaped before they are passed to my template, so I have no way of knowing if they will contain single or double quotes, or even both. Whichever way I try to handle the data my code ends up breaking because the quotes terminate the string declaration. I want to run a function on the data to escape quotes but I can't find a way to get the data into a valid variable first.
Is there any way to safely handle the data in JavaScript without it breaking a string variable declaration?
Edit: I'm posting code example;
CMS Text Input Field value is: Who'll win our "Big Contest"?
Text Input Field placeholder macro is [%TextInput%]
I'm building an HTML template for this input, using just JS/HTML/CSS
<script>
(function(){
var textInputStr = "[%TextInput%]";
})();
</script>
This will break the string declaration if the value of TextInput contains a single quote, and vice versa.
This is an awesome question, and one that deserves an answer. Strings in JS don't have a custom delimiter, like in most other modern languages, so you can get really stuck. But one solution is to build a script tag with the placeholder inside it, then find the innerHTML of that tag and grab the string back into a variable. eg
<script id="parseMe" type="text/template">
[%TextInput%]
</script>
then use
var yourString = document.getElementById("parseMe").innerHTML
Now you can manipulate the string as you please.
HTH!
I want to run a function on the data to escape quotes but I can't find a way to get the data into a valid variable first.
Well, you will have to make it a valid string literal before you could run JavaScript functions on it. There's no other way (unless you count an ajax request to the template script to get a string representation of it).
The input fields are not escaped before they are passed to my template
Then fix that. There's nothing you can do about it in JavaScript.
Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";
I have some addHtml JavaScript function in my JS code. I wonder how to escape HTML/JS code properly. Basically, what I am trying right now is:
addHtml("<a onclick=\"alert(\\\"Hello from JS\\\")\">click me</a>")
However, that doesn't work. It adds the a element but it doesn't do anything when I click it.
I don't want to replace all " by ' as a workaround. (If I do, it works.)
I wonder how to escape HTML/JS code properly.
To insert string content into an HTML event handler attribute:
(1) Encode it as a JavaScript string literal:
alert("Hello \"world\"");
(2) Encode the complete JavaScript statement as HTML:
<a onclick="alert("Hello \"world\""">foo</a>
And since you seem to be including that HTML inside a JavaScript string literal again, you have to JS-encode it again:
html= "<a onclick=\"alert("Hello \\"world\\""\">foo<\/a>";
Notice the double-backslashes and also the <\/, which is necessary to avoid a </ sequence in a <script> block, which would otherwise be invalid and might break.
You can make this less bad for yourself by mixing single and double quotes to cut down on the amount of double-escaping going on, but you can't solve it for the general case; there are many other characters that will cause problems.
All this escaping horror is another good reason to avoid inline event handler attributes. Slinging strings full of HTML around sucks. Use DOM-style methods, assigning event handlers directly from JavaScript instead:
var a= document.createElement('a');
a.onclick= function() {
alert('Hello from normal JS with no extra escaping!');
};
My solution would be
addHtml('<a onclick="alert(\'Hello from JS\')">click me</a>')
I typically use single quotes in Javascript strings, and double quotes in HTML attributes. I think it's a good rule to follow.
How about this?
addHtml("<a onclick=\"alert("Hello from JS")\">click me</a>");
It worked when I tested in Firefox, at any rate.
addHtml("<a onclick='alert(\"Hello from JS\")'>click me</a>")
The problem is probably this...
As your code is now, it will add this to the HTML
<a onclick="alert("Hello from Javascript")"></a>
This is assuming the escape slashes will all be removed properly.
The problem is that the alert can't handle the " inside it... you'll have to change those quotes to single quotes.
addHtml("<a onclick=\"alert(\\\'Hello from JS\\\')\">click me</a>")
That should work for you.
What does the final HTML rendered in the browser look like ? I think the three slashes might be causing an issue .