I\'m trying to store a JavaScript object in the URL of a web page (as a JSON string), but the URL contains some characters that will not work with HTML links.
On thi
You need to encode and decode with JSON
var link = document.getElementsByTagName('a')[0];
link.addEventListener('click', function(){
// this could also be done with location.hash = JSON.stringify(...);
var param = JSON.stringify(['your', 'array']),
href = '#'+this.getAttribute('href');
href += param;
location.href = href;
}, false);
// make string an object/array again
var obj = JSON.parse(window.location.hash.substr(1));
You can put a JSON string in an URL by URL-encoding it before putting it in the URL:
encodeURIComponent(JSON.stringify(object))
In your example, that would be:
http://jsfiddle.net/tsUpC/1/show/#%5B%22Hello%22%2C%22World!%22%5D
As you might guess, the opposite of encodeURIComponent is decodeURIComponent.