开发者

javascript string difference [duplicate]

开发者 https://www.devze.com 2023-01-01 10:36 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicates: single quotes versus double quotes in js
This question already has answers here: Closed 12 years ago.

Possible Duplicates:

single quotes versus double quotes in js

When to Use Double or Single Quotes in JavaScript

What is the diff开发者_如何学运维erence (if any) between the javascript strings defined below?

var str1 = "Somestring";

var str2 = 'Somestring';

"" and '' mean two very different things to me predominantly writing code in C++ :-)

EDIT: If there is no difference why are there two ways of achieving the same thing and which is considered better practice to use and why. Thanks!


Javascript treats single and double quotes as string delimiters.

If you use single quotes, you can use double quotes inside the string without escaping them.

If you use double quotes, you can use single quotes inside the string without escaping them.

Both examples evaluate to the same thing.

alert(str1 == str2); // true
alert(str1 === str2); // true

Why two ways? Due to the way javascript allows you to mix the two, you can write html attributes out without messy escapes:

var htmlString1 = "<a href='#'>link</a>";
var htmlString2 = '<a href="#">link</a>';

As for best practice, there is no convention. Use what feels best.

Personally, I like making sure the Javascript I emit matches the HTML (if I double quote attributes, I will delimit JS string with a ', so emitted attributes will use ").


In Javascript a string is a sequence of zero or more Unicode characters enclosed within single or double quotes (' or "). Double-quote characters may be contained within strings delimited by single-quote characters, and single-quote characters may be contained within strings delimited by double quotes.

In client-side JavaScript programming, JavaScript code often contains strings of HTML code, and HTML code often contains strings of JavaScript code. Like JavaScript, HTML uses either single or double quotes to delimit its strings. Thus, when combining JavaScript and HTML, it is a good idea to use one style of quotes for JavaScript and the other style for HTML.


No difference at all.


I believe the answer is there is no difference. They are both strings.

Here would be the usage of '

var mynewhtml = '<body class="myclass" ></body>';

or using "

var mynewhtml = "<body class='myclass' ></body>";

this also works but IMO is harder to read

var mynewhtml = "<body class=\"myclass\" ></body>";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号