html5 window.localStorage.getItemItem get keys that start with

前端 未结 4 1257
天命终不由人
天命终不由人 2021-01-14 01:22

How could I use

window.localStorage.getItem();

to specify items in localstarage that start with the string \'QQ\'. In my case the key

相关标签:
4条回答
  • 2021-01-14 01:53
    for ( var info in window.localStorage ){
     if ( info.substring( 0 , 2 ) === "QQ"){
      var data = window.localStorage.getItem( info ) );
      console.log(info);
     }
    

    code not tested

    0 讨论(0)
  • 2021-01-14 02:04

    Came across this and here is a solution in es6 :

    let search = 'QQ';
    let values = Object.keys(localStorage)
                       .filter( (key)=> key.startsWith(search) )
                       .map( (key)=> localStorage[key] );
    
    0 讨论(0)
  • 2021-01-14 02:05

    You don't, get all the items and check them individually (code not tested):

    var results = [];
    for (i = 0; i < window.localStorage.length; i++) {
        key = window.localStorage.key(i);
        if (key.slice(0,2) === "QQ") {
            results.push(JSON.parse(window.localStorage.getItem(key)));
        }
    }
    

    If you want to do queries use something like IndexedDB.

    0 讨论(0)
  • 2021-01-14 02:13

    I use this:

     var keyIndex = 0;
     var thisKey = window.localStorage.key(keyIndex);
    
     while(thisKey != '' && thisKey != undefined)
     {
        if (thisKey.substr(0, 2) == 'QQ')
        {
           // do whatever you need to do with thisKey
        }
    
        keyIndex+= 1;
        thisKey = window.localStorage.key(keyIndex);
     }
    

    But robertc's solution is right too, it's a bit more simple that way. I actually changed my code to do a for loop too.

    0 讨论(0)
提交回复
热议问题