I have a string:
var str = "username:joe_1987;password:123456;email:joe@mailmail.com;"
Can I (or rather,) how can I create an object out of in a way that I can call it's parameters, something like:
alert(obj.password)
and get 123456
I have a string:
var str = "username:joe_1987;password:123456;email:joe@mailmail.com;"
Can I (or rather,) how can I create an object out of in a way that I can call it's parameters, something like:
alert(obj.password)
and get 123456
I'm no expert, but something like this should work:
string = 'username:joe_1987;password:123456;email:joe@mailmail.com;';
array = string.split(';');
object = {};
for(i=0;i<array.length;i++){
if(array[i] !== ''){
console.log(array[i]);
object[array[i].split(':')[0]] = array[i].split(':')[1];
}
}
console.log(object);
I would recommend splitting on the semicolons in the string, giving you an array that will look like:
["username:joe_1987", "password:123456", "email:joe@mailmail.com"]
You can then apply the same idea to each element of this array, and then create the object. I've chucked a snippet below to explain:
var str = "username:joe_1987;password:123456;email:joe@mailmail.com;"
var splitBySemiColon = str.split(";");
splitBySemiColon.pop(); //Remove the last element because it will be ""
var obj = {};
for(elem in splitBySemiColon) {
splitByColon = splitBySemiColon[elem].split(":");
obj[splitByColon[0]] = splitByColon[1];
}
Hope this helps!
EDIT: Provided a live demo for you - https://repl.it/CtK8
IF you're certain the desired values won't have ;
or :
, you can just
var str = "username:joe_1987;password:123456;email:joe@mailmail.com;"
var obj = {};
str.split(';').forEach( function(segm) {
if(segm.trim()) { // ignore empty string
var spl = segm.split(':');
obj[ spl[0] ] = spl[1];
}
})
use this
var str = "username:joe_1987;password:123456;email:joe@mailmail.com;"
var data=str.split(';');
var obj={};
for(var i=0;i<data.length;i++){
var propArray=data[i].split(':');
obj[propArray[0]]=propArray[1]
}
There is no straight way. Just parse that string. For example:
var str = "username:joe_1987;password:123456;email:joe@mailmail.com;"
var arr = str.split(';');
var o = {};
for (a in arr) {
if (arr[a]) {
o[arr[a].split(':')[0]]=arr[a].split(':')[1];
}
}
console.log(o);