简体   繁体   中英

How to Parse an Array in Node.js?

What's the best way to parse:

[ 'Tue, 5 Apr 2011 15:15:59 +0100' ]
[ 'email@email.org' ]
[ 'User Name <admin@email.com>' ]
[ 'oi' ]

And take the [' '] out ?

Thanks

More details:

It's the heads of an IMAP e-mail.

msg.headers.date

returns the data, etc.

What I want is to have:

"Tue, 5 Apr 2011 15:15:59 +0100"
"email@email.org"
"User Name"
"admin@email.com"
"oi"

So you're saying that console.log(msg.headers.date) gives you [ 'Tue, 5 Apr 2011 15:15:59 +0100' ] ??

In that case, console.log(msg.headers.date[0]) == Tue, 5 Apr 2011 15:15:59 +0100

Is that what you're trying to get?


What is this? A file? Straight text? Part of a larger JSON structure?

Basically, convert it into an actual structure and load it, one way or another:

 
 
 
  
  module.exports = [ [ 'Tue, 5 Apr 2011 15:15:59 +0100' ], [ 'email@email.org' ], [ 'User Name <admin@email.com>' ], [ 'oi' ] ]; ---- var info = require('./file'); // info[0][0] == Tue, 5 Apr 2011 15:15:59 +0100
 
  

or if you want to parse it:

 
 
 
  
  var lines = [ "[ 'Tue, 5 Apr 2011 15:15:59 +0100' ]", "[ 'email@email.org' ]", "[ 'User Name <admin@email.com>' ]", "[ 'oi' ]" ]; var info = JSON.parse('[' + lines.join(',') + ']'); // info[0][0] == Tue, 5 Apr 2011 15:15:59 +0100
 
  

Assuming each line is an element in the array lines :

var lines = [
    "[ 'Tue, 5 Apr 2011 15:15:59 +0100' ]",
    "[ 'email@email.org' ]",
    "[ 'User Name <admin@email.com>' ]",
    "[ 'oi' ]"
];

for(var i=0;i<lines.length;i++){
    lines[i]=lines[i].replace(/^\[ *'|' *\]$/g,'');
}

console.log(JSON.stringify(lines));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM