I'm currently assigning the value of a field to a variable:
userName = document.getElementById('userName').value;
Then assigning that variable to localstorage:
localStorage.setItem('userName', JSON.stringify(userName));
Retrieving that item here:
var retrievedUserName = localStorage.getItem('userName');
Then trying to output the contents of the item into a HTML div:
document.getElementById("response-heading-name2").innerHTML = retrievedUserName;
...but when I check the HTML, it's outputting the string with double quotes around it: "My name"
Does anyone know why this is happening, and how I can stop the double quotes from appearing?
When using double quotes "" to create a string literal, the double quote character needs to be escaped using a backslash: \" .
To place quotation marks in a string in your code In Visual Basic, insert two quotation marks in a row as an embedded quotation mark. In Visual C# and Visual C++, insert the escape sequence \" as an embedded quotation mark.
This has nothing to do with local storage.
The quotes are added when you convert the data structure to JSON with JSON.stringify
.
You should convert the JSON back to a JavaScript data structure with JSON.parse
after you retrieve it from local storage.
The point of using JSON is to ensure that what you store is a string because local storage can only store strings.
Since you are getting the value of an input, you know that it will be a string. So you could dispense with JSON altogether and not JSON.stringify
it in the first place.
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