1

I have a string:

var str = "username:joe_1987;password:123456;email:[email protected];"

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

asked Aug 26, 2016 at 15:10
2

5 Answers 5

2

I would recommend splitting on the semicolons in the string, giving you an array that will look like:

["username:joe_1987", "password:123456", "email:[email protected]"]

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:[email protected];"
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

answered Aug 26, 2016 at 15:20
Sign up to request clarification or add additional context in comments.

Comments

2

I'm no expert, but something like this should work:

string = 'username:joe_1987;password:123456;email:[email protected];';
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);

https://jsfiddle.net/oej2gznw/

answered Aug 26, 2016 at 15:18

Comments

0

IF you're certain the desired values won't have ; or :, you can just

var str = "username:joe_1987;password:123456;email:[email protected];"
var obj = {};
str.split(';').forEach( function(segm) {
 if(segm.trim()) { // ignore empty string
 var spl = segm.split(':');
 obj[ spl[0] ] = spl[1];
 }
})
answered Aug 26, 2016 at 15:21

Comments

0

use this

 var str = "username:joe_1987;password:123456;email:[email protected];"
 var data=str.split(';');
 var obj={};
 for(var i=0;i<data.length;i++){
 var propArray=data[i].split(':');
 obj[propArray[0]]=propArray[1]
 }
answered Aug 26, 2016 at 15:24

Comments

0

There is no straight way. Just parse that string. For example:

var str = "username:joe_1987;password:123456;email:[email protected];"
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);

answered Aug 26, 2016 at 15:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.