Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 localstorage adding in double quotes

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?

like image 655
Martin Avatar asked Oct 12 '17 14:10

Martin


People also ask

How do you encode double quotes?

When using double quotes "" to create a string literal, the double quote character needs to be escaped using a backslash: \" .

How do you mention double quotes in a string?

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.


1 Answers

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.

like image 128
Quentin Avatar answered Sep 24 '22 01:09

Quentin