Getting information from a user-provided account list into an array in Javascript
Users will paste an account list in this format, with a username, a colon, and a password on each line.
username1:password1
username2:password2
username3:password3
username4:password4
What is the best way to 开发者_如何学JAVAseparate each line and then each part in Javascript? I'd really like it to be as simple as accounts[1].username or accounts[3].password to retrieve data. Thanks!
What you need is JSON. You need to parse that information and form the json objects array. Example from previous link
var myJSONObject = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
myJSONObject.bindings[0].method // "newURI"
I hope passwords are not allowed to have colons in them or they're encoded somehow prior to you having to split on a colon. :)
// for each account string, split it on a colon.
var accountString = 'username1:password1';
var accountInfo = accountString.split(':');
// initialize an accounts array.
var accounts = [];
// add a new item (in JSON format here) to the accounts array.
accounts.push({username : accountInfo[0], password : accountInfo[1] });
replace :
with ,password:
for each line
insert {username:
at beginning of each line
insert },
at end of line
trim last comma ","
concat with {accounts:[
+ modified string + ]}
this gives you a json string, eval it as json
精彩评论