Should I not escape the double quotes in "markup4" and such? To my surprize this plain works. If I replace them by the " thing it doesn't.
<script type="text/javascript">
function test3(){
document.getElementById('div21').innerHTML += '<div class = "markup4"><br>blablablabla1.<br><br></div><div class = "markup3"><br>blablabla2.<br><br></div>';
}
</script>
These work without escape:
innerHTML = "<div class = 'markup4'>";
innerHTML = '<div class = "markup4">';
Note: When the " used outside, the ' works properly inside. (and
the opposite)
These need the escape:
innerHTML = '<div class = \'markup4\'>';
innerHTML = "<div class = \"markup4\">";
Note: When you use the double quote outside and inside, the inside's
" needs to be escaped by \. (same for single quotes)
These will break:
innerHTML = "<div class = "markup4">";
innerHTML = '<div class = 'markup4'>';
escape should be used when you want to include quotes within the data,
ex: He said, "Please use this!" should get escaped like:
He said, \" Please use this !\".
Otherwise they work without any troubles.
Hope I've clarified.
First the string is parsed to an internal javascript string representation, so you first need to escape for javascript string literals. The result of this would be the same as what you already have - so no modification is needed.
Now you have
<div class = "markup4"><br>blablablabla1.<br><br></div><div class = "markup3"><br>blablabla2.<br><br></div>
Internally in javascript memory.
After this, it's just like you would write that as normal HTML, so of course, if you use " it will not work.
It can get pretty complicated to store strings that go through 2 different interpretations, which is why you shouldn't do this but use templating engines with the templates stored in other files or custom script elements on the page, which would allow you to focus only on the html interpretation.
Don't forget browsers render their own innerHtml based on what you give them which can cause problems if nesting innerHtml code.
I found the ' and " codes useful here.
Related
First, I'm not sure I've titled my question properly. Please feel free to correct me if needed.
My Issue:
I've created a variable, in jQuery called var siteTitle. This variable is available for other .js files to use and then get passed back to the .html page.
It all works great and there are no issues except when the var siteTitle will contain certain characters that need to be escaped. (quote, single quote, and ampersand to be specific)
What I would like to do is to use a bit of jQuery that would search a particular dom element and see if it is using any of those characters and then automatically escape them.
I've searched for some similar functions and can not seem to find exactly what I need ... the closet idea I have seen is something like this. Its not exactly what I need but it is something like what I am looking for.
pathto: function(path, file) {
var rtrim = function(str, list) {
var charlist = !list ? 's\xA0': (list + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
var re = new RegExp('[' + charlist + ']+$', 'g');
return (str + '').replace(re, '');
};
So, I am trying to write a function that will automatically convert those characters to be escaped or their html equivalent.
So, if the var siteTitle is used in a dom element like this:
<h1 class="titleText">' + siteTitle + '</h1>
I need to be able to make sure that any characters get escaped in that element.
Here is a jsFiddle that shows exactly what I am trying to do ...
https://jsfiddle.net/bbyrdhouse/5jb2fdsr/1/
Any help is greatly appreciated.
Since you're using jquery, use the .text() function to set the value into your HTML. It'll escape it appropriately.
var siteTitle = 'My Site "Title"';
$my('.titleText').text(siteTitle);
Also, in your fiddle, the siteTitle variable is not what you think it is, because the 2nd quotation closes that value since it's not yet escaped. I wrapped it in single quotes in my example.
Updated fiddle
So I know that you can use getElementById to change text inside a webpage.
Something like this for example:
document.getElementById("article").innerHTML = "Search engine is here.";
But how do I, for example, make the text clickable. I think about something like this, but this won't work obiviously:
document.getElementById("article").innerHTML = "<a onclick="myFunction()" href="#">Search engine is here.</a>"
So, does anyone have an idea how to do it? Do you need to use jQuery?
It doesn't work, because you have a syntax error. This is not related to jQuery. If you need quotes inside a string, you either need to escape the quotes in the string, or change the quotes. You can embed double quotes in single quoted string and vice versa, but to include double quotes in double quoted strings you need to escape them by adding a \ in front of the quote to escape.
Either one of the three options below will do the trick.
Escaping:
document.getElementById("article").innerHTML = "<a onclick=\"myFunction()\" href=\"#\">Search engine is here.</a>";
Single quotes in JavaScript, double in HTML:
document.getElementById('article').innerHTML = '<a onclick="myFunction()" href="#">Search engine is here.</a>';
Double quotes in JavaScript, single in HTML:
document.getElementById("article").innerHTML = "<a onclick='myFunction()' href='#'>Search engine is here.</a>";
A different approach would by to really construct the element through JavaScript. In this snippet you don't need to escape quotes or mix single and double, although it's still good to know about escaping, since you are inevitably going to need it if you keep doing JavaScript.
Anyway, for educational purposes:
var div = document.getElementById("article");
// Create a link element
var link = document.createElement('a');
// Set its properties, events and content
link.href = '#';
link.onclick = function() {
alert('clicked!');
}
link.innerText = 'Text content of the link';
// Add the link to the div
div.appendChild(link);
<div id="article"></div>
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);
Can anyone help me to convert this to proper JavaScript?
<script>var datePostForAll = '<div class='date-header'><data:post.dateHeader/></div>';</script>
Thank you!
:*
It is proper JavaScript. It's the same as writing:
<script>
var datePostForAll = "<div class='date-header'><data:post.dateHeader/></div>";
</script>
They're used ' instead of an apostrophe so they don't have to escape ' and " marks inside the string. The <data:post.dateHeader/> is custom Blogger markup and will be evaluated when it is run. Because the contents of <data:post.dateHeader/> may include quote marks, they chose to wrap the string in ' to prevent accidentally introducing unescaped elements into the string. Regardless, as this will be outputting a date, wrapping it in quotes should be fine.
<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.