This is for a website game. I am utilizing JSON’s functionality with localStorage. At times I need to remove an item from the JSON string based on it’s value. For some reason when I do this extra backspaces are added to the string which breaks the rest of my function. How do I alleviate this?
Here is what I’ve got. I’ve tried messing with removing JSON.parse and JSON.stringify at the end in different configurations but the output always seems to have extra backslashes, depending on the configuration of JSON.parse and JSON.stringify there are even more backslashes.
const starterInv = ["Helmet", "Healing_Kit", "Rope"];
localStorage.setItem("Inventory", JSON.stringify(starterInv));
let inventory = localStorage.getItem("Inventory");
let inventoryString = JSON.stringify(inventory);
const helmetString = /Helmet/g;
const matchHelmet = inventoryString.match(helmetString);
let numHelmet = matchHelmet.length;
// if there is more than one helmet
if(numHelmet > 1) {
removeItem = ""Helmet",";
// if there is only one helmet
}else if (numHelmet == 1) {
//tests to see if Helmet is in first position in the string
let isBegin = inventoryString.indexOf("Helmet");
//if Helmet is not in first available position remove leading comma
if(isBegin > 4) {
removeItem = ","Helmet"";
//if there are other items in list remove trailing comma
}else if (inventoryString.length > 14) {
removeItem = ""Helmet",";
// only thing left should be scenario where Helmet is only item in string
}else {
removeItem = ""Helmet"";
}
}
inventory = JSON.parse(inventoryString.replace(removeItem, ""));
localStorage.setItem("Inventory", JSON.stringify(inventory));