I have this function :
function change_this(my_str)
{
$('#myDiv').html('<input value=\''+my_str+'\'>');
}
When I call this function with this :
onclick=change_this('Test '');
I see in the debugger that ' has been turned to a quote, and therefore the script does not work.
So my question is: how can I send a quote inside a string to a JS function?
I'm sure I'm not the first person to face this issue, I googled but did not find any simple explanations / answers.
You have two problems. This is because you have HTML embedded in JavaScript embedded in HTML which you are then generating HTML from by mashing together strings of JavaScript. You switch languages so many often it makes my head spin.
Problem 1: Getting the right string into the function
To include a single quote inside a string delimited by single quotes in JavaScript, you must escape them with a \.
onclick="change_this('Test \'');"
There is no need to use character references here. There are no ' with special meaning in the HTML. You would need to use ' three times if you had used ' instead of " to delimit the attribute value.
I'd avoid onclick entirely and favour data- attributes and JS event binding.
<input type="button" data-foo="Test '">
$("[type=button]").on('click', function (event) {
change_this( $(this).data('foo') );
});
Problem 2: Getting the right string into the HTML attribute value.
With the approach you are taking, you would need to convert the ' to '. Note that you would have to do it programatically because if you had it in the onclick attribute then it would be converted to ' by the HTML parser before the JavaScript engine even saw it.
Don't use your current approach though. Mashing strings together to make HTML is a nightmare.
Use DOM or something jQuery that vaguely resembles DOM.
var input = $("<input />").val(my_str);
$('#myDiv').empty().append(input);
Related
I am using user input inside JavaScript. And of course to be safe my framework is changing some symbols to HTML codes. But for some reason that breaks my JavaScript. So for example this works:
<a onclick="alert('hello')">Hello</a>
But this doesn't:
<a onclick="alert('hel l' lo')">Hello</a>
Why doesn't the below work and how can I make it work?
' is HTML for '. The HTML is parsed and the result passed to the JavaScript compiler so your JavaScript is alert('hel ' lo') and you can't have an unescaped ' in a string literal delimited with ' characters.
Escaping data to make it safe to insert into HTML is not enough to make it safe to insert into JavaScript which is then inserted into HTML in turn.
Store the user input in a data-* attribute (which is plain HTML so you can use ' safely) and then read the attribute from your JavaScript.
You're inserting a character reference for a single quote '.
Even though you're using ', when it hits JavaScript, it's a quote mark. Therefore, you're ending the string literal and causing a syntax error.
Following my code:
<div onclick="this.innerHTML='<div onclick=\"<img src=/*how to do here?*//>\">abc</div>'">a</div>
I would like to do everything on one line, can I specify the address of the image with the current example code or not?
Use " to represent a " character in an HTML attribute value delimited with " characters.
(Use & to represent a & character in an HTML attribute value, so if you want to nest insanely then: ")
But don't do this.
Writing everything on a single line in not a virtue.
Writing JS in an onclick attribute instead of a .js file is not a good thing.
Use addEventListener and friends.
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]\"";
<button onClick="function("parameter")">Click</button>
<button onClick="function('parameter')">Click</button>
var variable = "value";
var variable = 'value';
Is there a difference?
No. They are interchangeable by design.
The only requirement is that you need matching pairs (either use " or ', but not both to signify a string).
See the spec for string literals:
StringLiteral:
" StringCharactersDQopt "
' StringCharactersSQopt '
When used within HTML, you need to be careful not to use the same delimiter in HTML attributes as the javascript ones (which is why your first example is not legal).
To function correctly you would need to change it to:
<button onClick='function("parameter")'>Click</button>
Yes, there's a difference when you mix it with HTML like you do: the first snippet will throw an exception because you need to escape the double quotes while the second will work (that's one of the reasons why you should avoid mixing markup with javascript). In pure javascript (a separate file) there's no difference.
The two are equivalent as long as the same one is used at both the beginning and end of the string literal. That said, choosing the correct one can avoid needless string escaping:
<button onClick="function("parameter")">Click</button> <!-- becomes -->
<button onClick="function('parameter')">Click</button>
var foo = "And the computer said: \"Hello, world!\""; // becomes
var foo = 'And the computer said: "Hello, world!"';
This has a clear advantage when using JavaScript to generate HTML, as is common in scripts using jQuery.
There is no difference. ' and " are interchangeable. Now you can't have a string like this: var my_var = 'hello world"; Opening and close quotes have to match. This does allow you to easily do: var my_variable = 'John says "I love JavaScript."' without having to escaping anything.
so this: <button onClick="function("parameter")">Click</button> won't work because you have opened and closed the onclick event prematurely "function("
It is the same. The only reason for having ' and " is, that you cannot nest them, for example, in given onClick example ->
onClick=" and there you need to use ' to encapsulate string "
The only time that there is a difference (that I am aware of) is in JSON: Double quotes are required around the keys and values.
And yes, everyone is right; Your first line should read like this or it will throw an error:
<button onClick='function("parameter")'>Click</button>
I prefer to use the double quotes only (if possible) because I'm used to C like languages (C, C++, C#) where string can be wrapped only with double quotes. (Single quotes is used, but to wrap char type)
To answer the question itself: same like all others said, no real difference - guess it exists to support cases when you mix JavaScript with HTML.
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 .