Are single quotes allowed in HTML?
Asked Answered
E

11

168

I am a big time user of using double quotes in PHP so that I can interpolate variables rather than concatenating strings. As a result, when I am generating HTML I often use single quotes for setting tag fields. For example:

$html = "<input type='text' name='address' value='$address'>";

Now this is far more readable to me than either

$html = "<input type=\"text\" name=\"address\" value=\"$address\">";

or

$html = '<input type="text" name="address" values="' . $address . '">' ;

From brief searches I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser. Thus I am wondering what browsers would have problems recognizing single quote HTML?

Egide answered 7/11, 2008 at 19:35 Comment(1)
possible duplicate of Is it better to use single or double quotes for HTML attributes?Windgall
V
160

This is similar to When did single quotes in HTML become so popular?. Single quotes around attributes in HTML are and always have been permitted by the specification. I don't think any browsers wouldn't understand them.

Veliavelick answered 7/11, 2008 at 19:38 Comment(1)
One thing I need to mention here is that some HTML clients (not necessary browsers) have compatibly issues on single quoting. One strange example is that in Hotmail if you use <img src='cid:xxx' ... /> to show a inline image it will not appear at all because the content id was ignored. You have to use `<img src="cid:xxx" ... /> instead.Joanjoana
F
59

As noted by PhiLho, although there is a widely spread belief that single quotes are not allowed for attribute values, that belief is wrong.

The XML standard permits both single and double quotes around attribute values.

The XHTML standard doesn't say anything to change this, but a related section which states that attribute values must be quoted uses double quotes in the example, which has probably lead to this confusion. This example is merely pointing out that attribute values in XHTML must meet the minimum standard for attribute values in XML, which means they must be quoted (as opposed to plain HTML which doesn't care), but does not restrict you to either single or double quotes.

Of course, it's always possible that you'll encounter a parser which isn't standards-compliant, but when that happens all bets are off anyway. So it's best to just stick to what the specification says. That's why we have specifications, after all.

Flooded answered 7/11, 2008 at 20:52 Comment(4)
+1 for the link to the XML standard. I know this is an old thread, but for completeness, people should pay particular attention to the AttValue grammar specification within the standard. If you can read EBNF (very similar to regular expressions) you will see that it allows the use of both single and double quotes to delimit attributes.Femininity
But HTML is based on SGML (it's XHTML which is based on XML) so quoting the XML spec isn't very useful…Tremain
The real confusion is whether single or double quotes in an attribute value always need escaped. It seems that if you use double quotes around the attribute value, then you have to escape double quotes, but not single quotes. If instead you use single quotes around the attribute value, then you'd have to escape single quotes, but not double quotes. And I think that's the whole point of allowing either. If you have a lot of double quotes in your value, you can avoid escaping them by using single quotes around the entire value, and vice versa.Blondell
The fact of the matter is, if you use an XHTML document mode you will run into Javascript interpreter problems where it tries to force any Javascript-created HTML to use double quotes, breaking attributes with unescaped double quotes inside of them. I ran into this problem in Firefox as well as IE several years ago.Futtock
C
17

I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser

That person is wrong.

Cloutier answered 7/11, 2008 at 19:41 Comment(4)
Not necessarily. I can create a browser in a few minutes that does not recognise single quotes for HTML fields. Of course, there will be a lot more that it doesn't recognise... ;PMisadventure
@LightnessRacesinOrbit "What do you mean this browser doesn't support CSS?!"Sailor
... or more importantly, "that browser (which does not) is dead meat". :PCarbonyl
@LightnessRacesinOrbit - but have you? Seems like anybody motivated enough to make an entire browser is going to put in the extra 5 minutes to make it accept single quotes.Cyanotype
E
12

As I was looking to find information on this in a much more recent version of the specification and it took me quite some time to find it, here it is:

From

HTML

Living Standard — Last Updated 17 September 2021

[...]

13.1.2.3 Attributes

Single-quoted attribute value syntax

The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('), and finally followed by a second single U+0027 APOSTROPHE character (').
In the following example, the type attribute is given with the single-quoted attribute value syntax:

<input type='checkbox'>

If an attribute using the single-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.

https://html.spec.whatwg.org/multipage/syntax.html#attributes-2

Epsilon answered 29/4, 2019 at 15:36 Comment(0)
L
7

Don't believe everything you see on Internet...
Funnily, I just answered something similar to somebody declaring single quotes are not valid in XHTML...

Mmm, I look above while typing, and see that Adam N propagates the same belief. If he can back up his affirmation, I retract what I wrote... AFAIK, XML is agnostic and accepts both kinds of quote. I even tried and validated without problem an XHTML page with only single quotes.

Levo answered 7/11, 2008 at 20:31 Comment(0)
P
5

Only problem is data going into TEXT INPUT fields. Consider

<input value='it's gonna break'/>

Same with:

<input value="i say - "this is gonna be trouble" "/>

You can't escape that, you have to use htmlspecialchars.

Platform answered 15/3, 2012 at 10:45 Comment(5)
You can however do: <input value='it&apos;s gonna break'/>Complice
I think the reason we have the option to using single or double quotes is to avoid having to escape characters in exactly this scenario. If you have only double quotes in your value, surround it with single quotes to avoid having to escape the double quotes like so: <input value="it's not gonna break"/> and vice versa: <input value='i say - "this is not gonna be trouble"'/>.Blondell
@Blondell is right. Besides: For content, consider not using "dumb quotes" in the first place, but “typographic quotes”: Peter’s bar, not Peter's bar. ☞ en.wikipedia.org/wiki/Quotation_mark#Quotation_marks_in_EnglishPlauen
This answer is the only sensible advice. Use htmlspecialchars, always. Variable interpolation is great syntactic sugar, but the flip side of the coin is that it easily leads to hard-to-spot XSS vulnerabilities.Theriot
“You can't escape that…” Well, I’d say HTML entities are a way of escaping.Flawy
N
1

I also tend to use single quotes in HTML and I have never experienced a problem.

Narcis answered 7/11, 2008 at 19:40 Comment(0)
C
1

I used single quotes in HTML pages and embedded JavaScripts into it and its works fine. Tested in IE9, Chrome and Firefox - seems working fine.

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
        <title>Bethanie Inc. data : geographically linked</title>
        <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
        <script src='https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false' type='text/javascript'></script>
        <script type='text/javascript'> 
        // check DOM Ready
        $(document).ready(function() {
            // execute
            (function() {
                /////////////// Addresses ///////////////////
                var locations = new Array();
                var i = 0;
                locations[i++] = 'L,Riversea: Comp Site1 at Riversea,1 Wallace Lane Mosman Park WA 6012'
                locations[i++] = 'L,Wearne: Comp Site2 at Wearne,1 Gibney St Cottesloe WA 6011'
                locations[i++] = 'L,Beachside:Comp Site3 Beachside,629 Two Rocks Rd Yanchep WA 6035'

                /////// Addresses/////////
                var total_locations = i;
                i = 0;
                console.log('About to look up ' + total_locations + ' locations');
                // map options
                var options = {
                    zoom: 10,
                    center: new google.maps.LatLng(-31.982484, 115.789329),//Bethanie  
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    mapTypeControl: true
                };
                // init map
                console.log('Initialise map...');
                var map = new google.maps.Map(document.getElementById('map_canvas'), options);
               // use the Google API to translate addresses to GPS coordinates 
               //(See Limits: https://developers.google.com/maps/documentation/geocoding/#Limits)
                var geocoder = new google.maps.Geocoder();
                if (geocoder) {
                    console.log('Got a new instance of Google Geocoder object');
                    // Call function 'createNextMarker' every second
                    var myVar = window.setInterval(function(){createNextMarker()}, 700);
                    function createNextMarker() {
                        if (i < locations.length) 
                       {
                            var customer = locations[i];
                            var parts = customer.split(','); // split line into parts (fields)
                            var type= parts.splice(0,1);    // type from location line (remove)
                            var name = parts.splice(0,1);    // name from location line(remove)
                            var address =parts.join(',');   // combine remaining parts
                            console.log('Looking up ' + name + ' at address ' + address);
                            geocoder.geocode({ 'address': address }, makeCallback(name, type));
                            i++; // next location in list
                            updateProgressBar(i / total_locations);


                        } else 
                       {
                            console.log('Ready looking up ' + i + ' addresses');
                            window.clearInterval(myVar);
                        }
                    }

                    function makeCallback(name,type) 
                   {
                        var geocodeCallBack = function (results, status) {
                            if (status == google.maps.GeocoderStatus.OK) {
                                var longitude = results[0].geometry.location.lng();
                                var latitude = results[0].geometry.location.lat();
                                console.log('Received result: lat:' + latitude + ' long:' + longitude);
                                var marker = new google.maps.Marker({
                                    position: new google.maps.LatLng(latitude, longitude),
                                    map: map,
                                    title: name + ' : ' + '\r\n' + results[0].formatted_address});// this is display in tool tip/ icon color
                                   if (type=='E')  {marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')};
Communicative answered 19/2, 2014 at 4:12 Comment(0)
C
-1

Recently i've experienced a problem with Google Search optimization. If has a single quotes, it doesn't seem to crawl linked pages.

Calley answered 18/3, 2015 at 13:17 Comment(1)
Is this just in <a href=''> attributes?Thermocline
A
-2

... or just use heredocs. Then you don't need to worry about escaping anything but END.

Approachable answered 24/4, 2013 at 17:53 Comment(2)
I believe you are referring to the heredoc capability in PHP.Parted
Not sure why this answer is downvoted given context of original question. It doesn't directly answer the double verses single quotes issue, but it does address the php escaping issue that lead to OP favouring single quotes in the first place. It could do with an example of usage however.Thermocline
I
-10

Single Quotes are fine for HTML, but they don't make valid XHTML, which might be problematic if anybody was using a browser which supported only XHTML, but not HTML. I don't believe any such browsers exist, though there are probably some User-Agents out there that do require strict XHTML.

Insolence answered 7/11, 2008 at 19:56 Comment(5)
the worse part is people that write HTML pages but mark them as XHTML because it's 'better'. fortunately this fad seems to be going down.Kettledrummer
I do not believe this statement about XHTML is true. Both " and ' are acceptable in XML, and the W3C validator accepts XHTML documents with single-quoted attributes. Perhaps this may be a confusion with XHTML eliminating unquoted attributes which are legal in HTML?Stridulate
Unless you serve your page as text/xhtml and not text/html browsers will render it as HTML, so HTML rules will apply. Regrdless, one on the w3C principles is NOT TO BREAk THE WEB. Because it works now, it will likely work tomorrow.Gigantic
XHTML requires pages to be well-formed XML, and XML allows either double or single quotes around attributes.Dyestuff
@SoftwareMonkey Actually, you need application/xhtml+xml or application/xml.Complice

© 2022 - 2024 — McMap. All rights reserved.