I currently have a loop generating a URL to appear on a page. I have a few URL's that have an apostrophe in the string that it returns. I am attempting to remove the apostrophe from the URL. I am familiar with the .replace method which is what I'm attempting to implement. I am declaring a variable at the start of the case and then using the variable newUrl
Code:
} else {
let newUrl = sectorHTML += "<a href=\"" + linkURLPart1 + linkURLPart2 + jsonData.Column1[r].ReportURL + "/\">
<span style=\"color:#000000;\">"
//linkURLPart 1 = new ; linkUrlPart2 = article;
json.DataColumn1[r].ReportUrl = people's-home
sectorHTML += "<div>";
newUrl = newUrl.replace("'", "")
}
Current output:
/new/article/people's-home/
expected output:
/new/article/peoples-home/
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
I have a variable, before I use that variable,I need to add string quotes to the value/data which is inside the variable using JavaScript need help
//i am getting like this //
var variable=king;
//i want to convert it with single quote//
variable=variable;
but i need the data inside variable should be in a single quotation.
You can concatenate the variable with your quotes like :
function addQuotes(value){
var quotedVar = "\'" + value + "\'";
return quotedVar;
}
And use it like :
var king = addQuotes('king');
console.log will display :
'king'
Edit : you can try it in the chrome/firefox console, I did it and it works perfectly when copy/paste from here.
var x = 'abc';
var sData = "\'" + x +"\'";
// sData will print "'abc'"
var x = 'pqr';
var sData = "\'" + x +"\'";
// sData will print "'abc'"
1) You can use doublequotes
var variable = "'" + variable + "'";
2) ... or You can escape single quote symbol with backslash
var variable = '\'' + variable + '\'';
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 + "' />";
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.