Single quote or double quote in javascript

I always see javascript writing style, but I don’t know why such code. For example, I have a variable.

var topic = "community"; 

And when I found out javascript, I saw that someone was encoded in jQuery like this, some code in the section.

  :contains("' + topic + '") 

But I think it can code that way.

  :contains(topic) 

Or: Contains ("subject")

What is the difference between the three?

+7
javascript jquery
source share
4 answers
 :contains("topic") 

this search for items containing the string "topic"

where as

  var topic = "community"; :contains(topic) 

the topic here becomes a "community" .. therefore he is looking for an element containing a "community";

good for that

 :contains("' + topic + '") 

I think the code is not complete.

  $('div:contains("' + topic + '")')..; //div for example sake 

it becomes

  $('div:contains("community")')..; //<-- just to make sure the string is encoded with `""` 
+6
source share

:contains("' + topic + '") will search for the string '(VALUE of topic)', including single quotes.

 :contains(topic) 

will search for the meaning of the topic without surrounding quotes.

 :contains("topic") 

will literally search for a topic.

0
source share

There is no difference between single quotes and double quotes, both are used to designate an element as a string.

 var s = "hello" var m = 'hello' m === s // true 

another example relates to string escaping, in case of:

 contains("' + topic + '") 

the theme actually refers to the variable, not the string, so quotation marks must be escaped so that the program can access the value of the variable. otherwise, he would not read the topic value of the variable, but simply printed the string "topic".

0
source share

Single quotes and double quotes are usually related to whether a string replacement will occur, but in JS it does not matter as far as I know.

the difference between 3 is that the first one is the assignment of a variable where a line replacement can be performed. the second passes the string as an argument, and the third passes the variable or constant topic

 var topicOne = "Community1"; function write(toOutput) { document.write(toOutput); } write(topicOne); write("topicOne"); write('topicOne'); 

so here comes 3:

 Community1 topicOne topicOne 

In PHP, however, the same code will act differently because a double quote means replacing a string

 <?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?

0
source share

All Articles