Reputation: 724
A little confusing however...
I have a long string somestringDIEmorestringKILLanotherstringDIEmorestring
and I have split that at KILL
so I have the array below:
["valueArray"]
[0] => "somestringDIEmorestring",
[1] => "anotherstringDIEmorestring"
Now I need to split the strings further where it says DIE, however they ideally need to be placed inside a single array so I can loop through them all and post them to their respected endpoints.
Ultimately I need something like this:
["valueArray1"]
[0] => "somestring",
[1] => "morestring",
[2] => "anotherstring",
[3] => "morestring"
OR:
["valueArray1"]
[0] => ["Array"]
[0] => "somestring",
[1] => "morestring"
[1] => ["Array"]
[0] => "anotherstring",
[1] => "morestring"
How is the best way to go about this? I've currently got a $.each
function set up but it's not working correctly:
$.each( valueArray, function( i, val ) {
valueArray1[i] = val.split('DIE');
});
Any help would be awesome! Or equally if there is a better way altogether to sort this out.
Thank you.
NOTE: I have to use strings as it's data coming from localStorage
Upvotes: 0
Views: 71
Reputation: 71384
You can simply split on a regex.
val.split(/DIE|KILL/);
Or, in context:
var val = ...; // your value read in from localStorage
var valArray = val.split(/DIE|KILL/);
This would get you a flat array like:
[
[0] => "somestring"
[1] => "morestring",
[2] => "anotherstring",
[3] => "morestring"
]
I would however suggest use of a better serialization format for storage of data in string in localStorage. Perhaps JSON would best do the trick. Here is an example of setting and getting structured data to localStorage via JSON serialization. You could do the same with objects, an array of objects, or whatever other data structure you might have that can be serialized to JSON.
// set value
var arrayToStore = [
"somestring"
"morestring",
"anotherstring",
"morestring"
];
localStorage.setItem('storedArray', JSON.stringify(arrayToStore));
//get value
var arrayFromStore = JSON.parse(localStorage.getItem('storedArray'));
This gives you MUCH more flexibility in terms of not having to conceive your own serialization format for any sort of data structure you might store.
Or better yet, write your own setter/getter class for working with local storage that you can use anywhere in your application. A simplified example:
var localStore = {
var set = function (key, value) {
localStorage.setItem(key, JSON.stringify(value));
return this;
}
var get = function (key) {
return localStorage.getItem(key);
}
};
// usage
localStore.set('storedArray', arrayToStore);
var arrayFromStore = localStore.get('storedArray');
Upvotes: 3