Skip to content

Instantly share code, notes, and snippets.

@n0m4dz
Forked from ungoldman/findLocalItems.js
Last active February 20, 2023 18:18
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save n0m4dz/77f08d3de1b9115e905c to your computer and use it in GitHub Desktop.
Save n0m4dz/77f08d3de1b9115e905c to your computer and use it in GitHub Desktop.
how to filter keys from localStorage with a regex
// returns an array of localStorage items in key/value pairs based on a query parameter
// returns all localStorage items if query isn't specified
// query can be a string or a RegExp object
function findLocalItems (query) {
var i, results = [];
for (i in localStorage) {
if (localStorage.hasOwnProperty(i)) {
if (i.match(query) || (!query && typeof i === 'string')) {
value = JSON.parse(localStorage.getItem(i));
results.push({key:i,val:value});
}
}
}
return results;
}
@awgeezrick
Copy link

awgeezrick commented Oct 31, 2019

Thank you! I soooooooo needed to find this today. =]

I did have to remove the JSON.parse in order for it to work for my stuff.

Thanks again.

@sparcbr
Copy link

sparcbr commented Jun 3, 2020

why do you need this line:
if (localStorage.hasOwnProperty(i)) {
?

@Alcoine
Copy link

Alcoine commented Nov 24, 2020

why do you need this line:
if (localStorage.hasOwnProperty(i)) {
?

i in localStorage iterates over all enumerable and non-Symbol properties not only over own properties

If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames() or perform a hasOwnProperty() check (propertyIsEnumerable() can also be used). Alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment