Single quote or double quote in javascript - javascript

I always see a write style in javascript but I don't know why code like this.
For example, I have a variable.
var topic = "community";
And when I learned javascript I saw someone coded in jQuery like this, some code in section.
:contains("' + topic + '")
But I think it can code just like this.
:contains(topic)
Or
:contains("topic")
What the differences between above three ?

:contains("topic")
this search for elements that contains "topic" string
where as
var topic = "community";
:contains(topic)
topic here becomes "community"..so it searchs for element that contains "community";
well for this
:contains("' + topic + '")
i guess the code is incomplete..
$('div:contains("' + topic + '")')..; //div for example sake
this becomes
$('div:contains("community")')..; //<-- just to make sure the string is encoded with `""`

:contains("' + topic + '") will look for the string '(VALUE of topic)', including the single quotes.
:contains(topic)
will look for the value of topic, with no surrounding quotes.
:contains("topic")
will look for literally topic.

There is no difference between single quotes and double quotes, both are used to mark an element as a string.
var s = "hello"
var m = 'hello'
m === s // true
the other example refers to escaping a string, in the case of:
contains("' + topic + '")
topic actually references a variable and not a string, therefore the quotes must be escaped in order for the program to get access to the value of the variable. otherwise it would not read the value of the variable topic but simply print the string "topic".

Single quotes vs double quotes usually has to do with whether or not string replacement will happen, but in JS it doesn't matter as far as I know
the difference between the 3 is that the first one is a variable assignment where string replacement can happen. the second one is passing a string as an argument and the third one is passing the variable or constant topic
var topicOne = "Community1";
function write(toOutput) {
document.write(toOutput);
}
write(topicOne);
write("topicOne");
write('topicOne');
so here is what the 3 will output:
Community1
topicOne
topicOne
In PHP however the same code will act differently because the double quote implies string replacement
<?php
$topicOne = "community1";
$topicTwo = "community2$topicOne";
function write($toOutput) {
print $toOutput;
}
write($topicOne);
write("$topicOne");
write('$topicOne');
write($topicTwo);
write("$topicTwo");
write('$topicTwo');
?>
will produce a different output
community1
community1
$topicOne
community2community1
community2community1
$topicTwo
see where the difference is?

Related

JS Events help - when changing a style property

I have a code here that i was supposed to make to change a style property, managed to make it work, but had to look up at the proper way to place the ', the " and the + .
document.getElementById('image').style.backgroundImage="url('" + element.src + "')";
I have no issue understanding how structurally this works, my only question resides on why of the extra ', extra " and extra + inside where you call for the element.src.
originally i did something like this, and it obviously didnt work, why did those ('" + and + "') make the code work...
any help is appreciated
cheers
document.getElementById('image').style.backgroundImage="url(' element.src ')";
Let's analyze everything from your first code segment and that should give you a better understanding:
document.getElementById('image').style.backgroundImage="url('" + element.src + "')";
document is a variable
getElementById is a function, with the string 'image' being a parameter for that function.
style is a property
backgroundImage is a property which must be and must take a string
"url('" is a string
element is a variable, an object in this case, with src being one of its properties.
"')" is a string
The + signs are used to concatenate the string formed from "url('", element.src and "')". In short you are saying, "make a string from "url('", element.src and "')" and assign that string to the property backgroundImage.
Whereas in this:
document.getElementById('image').style.backgroundImage="url(' element.src ')";
The browser has no idea that element.src is a variable and not part of the string, since you enclosed it int double quotes, signaling that everything between the quotes is a string.
element is a variable outside of a string literal, but inside a string literal it is just the word element.
const element = "Hello!";
const first = "start element end";
const second = "start " + element + " end";
console.log({first,second});
Inside of CSS, you have to put your URL inside of quotes or apostrophes, so that has to translate to the javascript as well.
When you call the DOM event it will do this:
Original tag:
<div src="http://example.com/image.png"></div>
after calling the javascript function:
<div style="background-image: url('http://example.com/image.png');" src="http://example.com/image.png"></div>
and because you need to have some sort of quotation in the URL syntax, you have to use a different kind of quotation, such as the '' in this case.
For more reference on the background image style, you can go here: https://www.w3schools.com/css/css_background_image.asp
but to completely answer your question, the + in there is used to say that you want to add something else there, such as another string or a variable.
More information on that here: https://www.w3schools.com/jsref/jsref_operators.asp (you have to scroll down a bit to the string operators section).

How to "Quote" a String in jQuery?

Info's: I have some javascript code that i will show below, who i'm having problem with quotes.
html = [];
style = 'class=odd';
html.push('<li '+style+' onclick=SelectItem("'+ele.id+'","'+idItem+'","'+dsItem+'","'+qtItem+'"); >'+id+' - '+$iObjItensListaVenda.result.ds_item[i]+'</li>');
I have strings that i get from a JSON Object, as you see above.
Problem: But when i'm trying to place it as a Function Parameter on the onClick event of the <li> element, my resulting html <li> element becomes totally unformatted like that:
<li natural,"150");="" white="" american="" onclick="SelectItem("descItem1","2",TELHA" class="odd">00002 - TELHA AMERICAN WHITE NATURAL</li>
What do i want: i need a solution like a function, maybe already exists in jQuery, to Quote my String. Like a QuoteStr("s t r i n g"); to become ""s t r i n g"".
Maybe you're complaining about:
The variable ele is a html <input> element.
The variable idItem contains only numbers, they come from a JSON Object.
The variable dsItem its a string containing Item Description, it comes from the JSON Object too.
The variable qtItem contains only numbers, it is the quantity of the items, it comes from the JSON too.
The sane solution would be to use jQuery to build the element and bind the event handler, not building an HTML string:
var $li = $('<li />', {
"class": "odd",
on: {
click: function() {
SelectItem(ele.id, idItem, dsItem, qtItem);
}
},
text: id + ' - ' + $iObjItensListaVenda.result.ds_item[i]
});
If you are doing this in a loop and the variables end up having the wrong values, please see JavaScript closure inside loops – simple practical example. Alternative you could use jQuery's .data API to set and get those values.
Try \" instead of ' in onClick
$(".container").append("Edit");
You can use quotes in a string by escaping them with a backslash.
var text = "s t r i n g";
"\"" + text + "\"" === "\"s t r i n g\"";
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
You can always use backslash to escape quotes:
console.log('te\'st'); // te'st
console.log("te\"st"); // te"st
You can do the same thing for your string, but I'd suggest you rewrite the whole thing into something more usable. By that I mean not using strings to build objects, but building objects directly.
For example:
var li = document.createElement('li');
li.className = myClass;
li.onclick = function(){/*...*/};
It gets even easier with jQuery.

How to find number string inside delimited string

I've been working on this all day and just cannot seem to figure out why it won't work. I am grabbing a delimited string from a hidden field. I need to test to see if a string is contained in that original string. The simple example below should work but does not.
var orgStr = "091300159|091409568|092005411";
var newArr = orgStr.split('|');
console.log(orgStr);
console.log(newArr);
console.log("inarray? " + $.inArray(newArr, "092005411"));
It seems to work if I can wrap quotes around each value but all attempts are unsuccessful.
In JQuery's inArray function the value needs to come before the array.
console.log("inarray? " + $.inArray("092005411", newArr));
You could also use the native indexOf operator as such:
console.log("inarray? " + newArr.indexOf("092005411"));
Both should output "inarray? 2" to the console.
Have a look at the $.inArray docs.
The first argument is the value and the second the array. You did the opposite.
$.inArray("092005411", newArr) correctly returns 2.

how to force jquery attr() to add the attribute with single quotes

I create an in memory div:
var video_div = document.createElement('div');
video_div.className = "vidinfo-inline";
In essence I have some variables:
var key = "data-video-srcs";
var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';
And I use jquery to add that data attribute to the div:
$(video_div).attr(key, value);
Here is my problem. After doing that I get this:
<div class="vidinfo-inline" data-video-srcs="{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}"></div>
And that doesn't work putting that json in there. It has to be in single quotes. It has to look like this:
<div class="vidinfo-inline" data-video-srcs='{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}'></div>
As later on I do something like this:
var video_srcs = $('.vidinfo-inline').data('video-srcs');
And that won't work unless the json is in single quotes.
Does anyone have any ideas?
EDIT:
According to jquery: http://api.jquery.com/data/#data-html5
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.
Thus I can't escape the double quotes, it has to be inside single quotes. I have a work around and I'll post that as an answer unless someone else has a better answer.
I have a workaround. And if anyone has a better solution, I'd love to see it.
I wrote a replace method:
var fixJson = function(str) {
return String(str)
.replace(/"{/g, "'{")
.replace(/}"/g, "}'");
};
So basically I send the html into this function and insert it into the DOM.
For example:
var html = htmlUnescape($('#temp_container').html());
html = fixJson(html);
I realize that has some code smell to it. I mean, going through everything on that element just to fix the double quotes to single quotes stinks. But for lack of other options or ideas, it works. :\
Replace the double quotes with HTML entities:
var value = '{"video1":"http://www.youtube.com/watch?v=KdxEAt91D7k&list=TLhaPoOja-0f4","video2":"http://www.youtube.com/watch?v=dVlaZfLlWQc&list=TLalXwg9bTOmo"}';
# Naive approach:
value = value.replace('&', '&').replace('"', '"');
# Using jQuery:
var $tmp = jQuery('<div></div>');
value = $tmp.text(value).html();
// Then store it as normal

Why is my .data() function returning [ instead of the first value of my array?

I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:
var stuff = $('div').data('stuff');
alert(stuff[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<div data-stuff="['a','b','c']"></div>
Why does this appear to alert '[' and not 'a' (see JSFiddle link)
JSFiddle Link: http://jsfiddle.net/ktw4v/3/
It's treating your variable as a string, the zeroth element of which is [.
This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.
If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)
<div data-stuff='["a","b","c"]'> </div>
var stuff = $('div').data('stuff');
When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.
Declaring it as an attribute means that it is a string.
So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);
You need to make it look like this:
<div data-stuff="a,b,c"></div>
var stuff = $('div').data('stuff').split(',');
alert(stuff[0]);
Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.
However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.
As others have identified the value is treated as string so it is returning "[". Please try this (aaa is the name of the div and I took out the data-stuff):
$(function(){
$.data($("#aaa")[0],"stuff",{"aa":['a','b','c']});
var stuff = $.data($("#aaa")[0],"stuff").aa;
alert(stuff[0]); //returns "a"
});
A different approach is posted at jsfiddle; var stuff = $('div').data('stuff'); stuff is a string with 0th character as '['
Well, var stuff = eval($('div').data('stuff')); should get you an array

Categories