I'm working on an application that will use HTML5 localStorage. I can't find anywhere whether there are any restrictions on the key besides the fact that it must be a string.
Specifically I'd like to know if I can use a URL as a key in localStorage across all browsers that support localStorage (eg, are symbols like :/?#._-=+@!$%^&*()[]{}|<>
allowed to be used in the key?).
Also: what about whitespace? Is that allowed in a localStorage key across browsers?
I found this topic but it only appears to have tested acceptable strings in localStorage values (not keys).
The localStorage is an instance of the Storage type that allows you to store persistent data in the web browsers. The localStorage can store only strings. To store objects, you convert them to strings using the JSON.
The key() method returns name of the key with the specified index. The key() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.
You can store the value in localStorage with the key value pair. It has two methods setItem(key, value) to store the value in the storage object and getItem(key) to retrieve the value from the storage object. document. getElementById("result").
The specification requires keys and values to be set and returned as a DOMString
type value. DOMString is described in [DOM Level 3 Core][1] as:
A DOMString is a sequence of 16-bit units. IDL Definition valuetype DOMString sequence<unsigned short>;
The UTF-16 encoding was chosen because of its widespread industry practice. Note that for both HTML and XML, the document character set (and therefore the notation of numeric character references) is based on UCS [ISO/IEC 10646]. A single numeric character reference in a source document may therefore in some cases correspond to two 16-bit units in a DOMString (a high surrogate and a low surrogate). For issues related to string comparisons, refer to String Comparisons in the DOM.
For Java and ECMAScript, DOMString is bound to the String type because both languages also use UTF-16 as their encoding.
So officially, any legal UTF-16 string is legal as a key or a value. Not every UTF-16 codepoint is a legal character though so you should try to avoid certain symbols like "surrogate pairs", "byte-order marks" and "reserved characters".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With