For anyone interested, I ended up building a "localstorage with expirations" script here, http://plugins.jquery.com/project/localcache
What I'm doing: building an extension for Storage, so that the user can do this:
localStorage.setThing(key, value)
and the user can do the following:
localStorage.setThing("key1", 1)
localStorage.setThing("key2", "this is a string")
localStorage.setThing("key3", { prop1: "this is a json obj" })
In my setThing method, I'm checking for the typeof for value, and if typeof value == "object"
, I'm storing it as localStorage.setItem(key, JSON.stringify(value))
On the getThing method, I know that the value that makes it into localStorage is always going to be a string. So, how can I do this?
var val = localStorage.getItem("key3")
if (val is a previously JSON.stringify'd object) // <-- ??
return JSON.parse(val)
Do I need to do a regex check on val, and if so, does anyone have a pattern handy which tells me if a string is really a JSON.stringify'd object?
Thanks!
The usual way to tell if a string is JSON is to run it through a JSON decoder. If it succeeds, it is JSON :-) No need for a regex here.
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