get value from key in sessionStorage javascript

3.1k Views Asked by At

Is it possible to check if a specific value exists in a key in sessionStorage?

Let's say that I have a key that is named "item" and I got digits in that key. I want to check if the digit "5" exists in item.

I have tested to write like this:

  if(sessionStorage.getItem("item") == "5");

but It doesn't respond as i want.

Is there another way I can check if the digit 5 exists in item?

3

There are 3 best solutions below

0
On

Use this:

sessionStorage.setItem("item", "53");
if (sessionStorage.getItem("item").indexOf("5") > -1) {
    // sessionStorage item has number "5"
}
9
On

I dont know if I understood you correctly, but I assume you have item in your session storage, e.g.:

sessionStorage.setItem("item", 12345)

Then, you want to check if there is a number 5 in it. You can do it by typing

sessionStorage.getItem("item").indexOf(5) > -1

0
On

sessionStorage is returning the value as a string and not as an object array. So you can first use split to get the array you set in initially.

So whether you do this:

sessionStorage.setItem("item", [1,2,3])

or this:

sessionStorage.setItem("item", ["1","2","3"])

sessionStorage.getItem("item") will return this: "1,2,3" (string)

After splitting your string,

if(sessionStorage.getItem("item").split(",").indexOf("5") > -1){
  //do your computation
}
if(sessionStorage.getItem("item").split(",").includes("5")){
  //do your computation
}