js: please explain this variable value with 5 double quotations - javascript

Please, take a brief look at the code below:
<script type="text/javascript">
function recentpostslist(json) {
document.write('<ul class="recommended">');
var i;
var j;
for (i = 0; i < json.feed.entry.length; i++)
{
for (j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
break;
}
}
var postUrl = "'" + json.feed.entry[i].link[j].href + "'";//bs
var postTitle = json.feed.entry[i].title.$t;
var item = "<li>" + "' + postTitle + " </li>";
document.write(item);
}
document.write('</ul>');
}
</script>
<script src="https://xxxxxxxxxx.blogspot.com/feeds/posts/summary/-/recommended?max-results=3&alt=json-in-script&callback=recentpostslist"></script>
Background info
I found this somewhere on the Internet yesterday, and have been trying to modify it a bit, since.
Variables i and j were originally declared within the for loop, as in...
for (var i = 0; i < json.feed.entry.length; i++)
{
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
break;
}
}
...
...but after doing a bit of (beginners') reading on w3schools.com, I got the impression that they're recommending keeping the variables declaration outside the for loop. My programming skills are scant, at their very best, so truth be told, I have no idea whether my impression was right.
Then I assigned a class to the <ul> element at the beginning (3rd line).
So far, so good. I checked, and the script was still working.
What it does is list the titles of a blog's 3 latest posts that have been labeled "recommended".
Then I made an attempt to assign a class to the <li> element that's declared as a... ehm... part of the value (have I understood that right?) of the item variable on line 15:
var item = "<li>" + "' + postTitle + " </li>";
But that seems to invalidate the code, which came as no surprise, really, since it did seem like a bit of a long shot.
My question
When taking a closer look at this line of code, however, I must say I was quite baffled by all the quotation marks (single and double).
It would be greatly appreciated if someone could explain
"<a href="+ postUrl + '" target="_blank">'
Why are there 5 double quotations in total? Is it incorrect?
What function does '" target="_blank">' serve?

You're using JS to create the string <a href="some-url.html" target="_blank">
All of the quotes are necessary because you're using quotes in JS to define a string literal, but also outputting quotes in the string itself - thus, the use of single quotes around double quotes. '"' in JS creates the string ".
target="_blank" is an HTML attribute that says the target window the hyperlink opens in should be called _blank, aka, a new window.

The "<a href="+ postUrl + '" target="_blank">' as a whole statement is used to dynamically build an anchor tag <a> by reading the postUrl from the feeds json, and then append this <a> tag to your html.
The first two " quotes are used to define a string literal containing the first segment of the <a> tag, while the last two " are to contain the value of the target attribute which will be shown on the final HTML, the one in the middle (the 3rd in order) is used to close the href attribute when viewed on your HTML.
This way the rendered HTML will be as following:
<a href="http://the_postUrl_value_from_feed" target="_blank">
BTW, the statement you're using is wrong, it is missing the starting " quote of the href attribute, try updating it to be as following:
'<a href="' + postUrl + '" target="_blank">'

It's just using single quotes to avoid having to escape the literal double quotes in a double-quoted string.
'" target="_blank"'
vs
"\"target=\"_blank\""
Since the definition of postUrl includes the quotes for the attribute, your definition of item has an extra double quote in it. However, I would recommend not putting those quotes postUrl, because the quotes are not part of the URL.
If you do that, there is a missing double quote earlier in the line. You have
var item = "<li>" + "' + postTitle + " </li>";
and you should have
var item = "<li>" + '' + postTitle + " </li>";
# ^^^^^^^^^^^
# Include a literal " after the =,
(Otherwise, the quote preceding target would be extraneous and need to be removed.)
The line would be a little clearer as
var item = '<li> ' + postTitle + " </li>";
and you can blame JavaScript for not having a built-in, convenient way to interpolate values into a string. (Although, see How can I do string interpolation in JavaScript?, which suggests that this has been added. Note, I am not a Javascript programmer.
var item = `<li> ${postTitle} </li>`;
)

To answer your question I have to explain something about string variables.
Lets take a look to the code where you filled your var item:
var item = "<li>" + "' + postTitle + " </li>";
Here you're making a string variable, so the quote (double or single) has to start and end the string and has to be the same, like this:
var myVar = "My content";
Follwing the code you have a variable that will be put inside another variable, so you have to open the quote, put your string, then close your quote, put the + sinal to concat string and finish (or put another + to concat with another string/var). Example:
var myAge = "23";
var myConcatVar = "I am " + myAge + " years old";
This is the basic, about concat and string.
But you are making a HTML string, and HTML code use quotes.
So, yes, you have to use all that quotation (double and single).
Now about your code:
As you presume, you have to start a string with double or single quotation, but you have to keep this quotation when you concat. In the var item you start with double quotation but use single quotation to concat with postUrl var. Your code look like this:
var item = "<li>" + "' + postTitle + " </li>";
When he must be like this:
var item = "<li>" + "<a href='"+ postUrl + "' target='_blank'>" + postTitle + "</a></li>";
Then when you print this var, the result will be like:
<li><a href='postUrl content' target='_blank'></a></li>
As you see in the result, you have to use the single and double quotation, because the atribute href and target use quotation too.
And about the target="_blank", it will send the url in a new tab.
I'm sorry for my bad english haha, and I hope this helps.

Ok, so this line has a messed up quotation mark.
var item = "<li>" + "' + postTitle + " </li>";
Give it a try with this one:
var item = "<li>" + "<a href="+ postUrl + " target='_blank'>" + postTitle + "</a></li>";
The problem was the single quote after the postUrl +...
You are already escaping the URL properly so no need for additional quotes around postUrl.
Give it a try!

The original has three " which means one is never closed so it wouldnt work. the correct one would be
" target='_blank'"
verses
'" target="_blank"'
In javascript there are a few ways to make strings two ways are ' ' single ticks and " " double ticks.
Everytime you start a tick (", ') everything inside of it is a string until a corresponding closing tick (", ') so if you need to have a string inside of a string you can accomplish this by doing either single ticks inside of double ticks or double ticks inside of single ticks. Run this in the web console
console.log("hey 'yes'");
console.log('hey "yes"');
verses
console.log("hey "yes"");
console.log('hey 'yes'');
the last to will error because you are now saying string of hey and then variable yes with closing empty string

Related

Escaping user inputs to prevent issues with code

I have some user provided variable that gets inserted into a script. Normally this works well, but fails when certain characters such as quotes are used. Is there a way to escape this?
document.getElementById("test").innerHTML = "<div oncontextmenu='javascript:alert(" + var1 + ");return false;'>" + var2 + "</div>";
Try using:
document.getElementById("test").innerHTML = `<div oncontextmenu='javascript:alert(${var1});return false;'>${var2}</div>`;
Convert your string to Template literal with use of backticks( ` symbol)
document.getElementById("test").innerHTML = `<div oncontextmenu='javascript:alert(` + var1 + `);return false;'>` + var2 + `</div>`;

Replace illegal character in javascript string with the legal one

how do I replace illegal character in a javascript code? I found a lot of solution to strip them off the string but none to actually keep the char there.
here an example line:
document.getElementById("popupcontent").innerHTML += "<img class='popupbanner' src='" + eventcontent[date][i]['bannerimg'] + "' />";
So in my function, it make my "for" loop not working properly as soon as the following char are in a string: <, >, /
any help is appreciated.
regards,
You can replace characters in javascript using the replace() function. Please see this stackoverflow post.
You can have the browser automatically escape the stuff for you:
function escape(string) {
var target = document.createElement('div');
target.appendChild(document.createTextNode(string));
return target.innerHTML;
}
Then use it by:
var escapedString = escape(eventcontent[date][i]['bannerimg']);
document.getElementById("popupcontent").innerHTML += "<img class='popupbanner' src='" + escapedString + "' />";

append single quotes to characters

I have a string like
var test = "1,2,3,4";
I need to append single quotes (' ') to all characters of this string like this:
var NewString = " '1','2','3','4' ";
Please give me any suggestion.
First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').
var test = "1,2,3,4";
var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");
JS Fiddle demo (please open your JavaScript/developer console to see the output).
For multiple-digits:
var newString = test.replace(/(\d+)/g, "'$1'");
JS Fiddle demo.
References:
Regular expressions (at the Mozilla Developer Network).
Even simpler
test = test.replace(/\b/g, "'");
A short and specific solution:
"1,2,3,4".replace(/(\d+)/g, "'$1'")
A more complete solution which quotes any element and also handles space around the separator:
"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")
Using regex:
var NewString = test.replace(/(\d+)/g, "'$1'");
A string is actually like an array, so you can do something like this:
var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
testOut += "'" + test[i] + "'";
}
That's of course answering your question quite literally by appending to each and every character (including any commas etc.).
If you needed to keep the commas, just use test.split(',') beforehand and add it after.
(Further explanation upon request if that's not clear).

How to append text to all values of javascript Array

Basically, I need to convert a string
"23423,1616,3461743,1345"
to a string
"<img src='23423'></img><img src='1616'></img><img src='3461743'></img><img src='1345'></img>
So far I have tried:
var PhotoArray=JSONeventobject.Events[i].FileNameArray.split(","); // Just convert this string to array
for (i = 0; i < PhotoArray.length; i++) {
PhotoArray[i] = "<img src='"+PhotoArray[i]+"</img>";
}
var Photostring = PhotoArray.toString().replace(",", "")
But this causes my browser to crash. It makes sense to me :/
Some terrible answers here. Try:
"1,2,3,4".split(",").map(function(a) { return "<foo>" + a + "</foo>"; }).join("");
Or with slightly more modern Javascript:
"1,2,3,4".split(",").map(a => `<foo>${a}</foo>`).join("");
Also please be aware of HTML injection.
You need to make sure you close your image tag. Another thing that may cause the problem is that i is undefined. Does your browser give an error message?
var str = "23423,1616,3461743,1345";
var PhotoArray = str.split(",");
for ( var i = 0; i < PhotoArray.length; i++ ) {
PhotoArray[i] = "<img src=\"" + PhotoArray[i] + "\"></img>";
}
str = PhotoArray.join("");
There isn't an </img> tag in HTML, so you don't need that.
In PhotoArray[i] = "<img src='"+PhotoArray[i]+"</img>"; you're not ending the image tag, this will produce <img src='1616</img> which is why it gives strange results. Try PhotoArray[i] = "<img src='"+PhotoArray[i]+"'>"; instead.
If you don't want to use a loop (and I didn't want to use a loop), you could do this:
var str = "23423,1616,3461743,1345";
str = ("," + str + ",").split(',').join("'></img>,<img src='").split(",").slice(1,-1).join('');
console.log(str);
What it's doing is adding a comma on either side of the list, splitting the string into an array based on those commas, then adding the img tags on either side with the join call, splitting again based on the command between opening img tag and closing img tag we just put in, burning the first and last elements in the array, and then finally joining them all back together into a single string.
The console output is:
<img src='23423'></img><imgsrc='1616'></img><img src='3461743'></img><img src='1345'></img>
Nothing like an ugly one line solution!
In addition to what #mikel says --
You're using the same variable, i, as your index into JSONeventobject.Events and as your index into PhotoArray. Without seeing the rest of your code, I don't know whether that's going to be a problem, but it's worth checking.
Also, rather than converting to an array and back, it seems simpler to just write:
var Photostring = "<img src='" + JSONeventobject.Events[i].FileNameArray.replace(/,/g, "'/><img src='") + "'/>";
(that is, replace all the commas with '/><img src=', prefix the first element's <img src=', and append the last element's '/>).
Is the variable 'i' declared as var?
#1 str.split([separator[, limit]])
split function
splits a string into an array
based on separator we give. limit is optional.
#2 arr.map(callback[, thisArg])
map function
returns new array
that is formed
from result of
calling "callback" function
for each element in "arr".
thisArg is optional.
#1 str.split([separator[, limit]])
join function
joins all elements of an array, into a string. limit is optional.
So, answer is:
var photoString = "23423,1616,3461743,1345";
var photoArray = str.split(",").map(
function(a) {
return '<img src="' + a + '"></img>';
}
).join("");
Sources:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join

jquery - assign variable inside a .html()

i++;
$("#test").html("<iframe id='i' src='arr[0]'></iframe>");
I want to assign the value of the array to the iframe source as shown here. This doesn't work however. How is this possible? Thanks
$("#test").html("<iframe id='" + i + "' src='" + arr[0] + "'></iframe>");
You need to use concatenation:
$("#test").html("<iframe id=\"" + i + "\" src=\"" + arr[0] + "\"></iframe>");
Edited to match updated question
Why your code doesn't work as expected:
$("#test").html("<iframe id='i' src='arr[0]'></iframe>");
generates the html output:
<div id="test">
<iframe id='i' src='arr[0]'></iframe>
</div>
Your variables are in fact outputted as literals, since you're not using any escaping/concatenation (see this article for JS string 101).
What you can do to make it work:
While the other answers are correct, consistently using single quotes for strings makes HTML concatenation way more fun (as attribute values should usually be in double quotes):
i++;
$("#test").html('<iframe id="' + i + '" src="' + arr[0] + '"></iframe>');
What you can do to make it work even more hassle-free for you:
It might be overkill if you need to concatenate just once. In the long run though, this approach by #Zippoxer makes your life much easier when you have to insert values into strings:
String.prototype.format = function() {
var formatted = this;
for(arg in arguments) {
formatted = formatted.replace("{" + arg + "}", arguments[arg]);
}
return formatted;
};
Usage in your case:
$("#test").html('<iframe id="{0}" src="{1}"></iframe>'.format(i, arr[0]));
try this...
$("#test").html("<iframe id='" + i + "' src='" + arr[0] + "'></iframe>");
What you are doing with $("#test").html("<iframe id='i' src='arr[0]'></iframe>"); is setting the id to the literal character "i" and setting the src to the literal string "arr[0]" rather than the values of these variables.

Categories

Resources