【发布时间】:2013-06-02 17:36:25
【问题描述】:
我想在 Javascript 中将以下几行拆分成一个数组:
Jun 02 16:45:04 [steveh] [info] test1
Jun 02 16:45:12 [steveh] [info] test2
Jun 02 16:45:12 [steveh] [info] test3
test 3.1
test 3.2
Jun 02 16:45:16 [steveh] [info] test4
我可以这样做:
var arr = data.split(/\r?\n/);
这让我明白了:
[
"Jun 02 16:45:04 [steveh] [info] test1",
"Jun 02 16:45:12 [steveh] [info] test2",
"Jun 02 16:45:12 [steveh] [info] test3",
"test 3.1",
"test 3.2",
"Jun 02 16:45:16 [steveh] [info] test4"
]
到目前为止一切顺利,但问题是,我不想要该数组中的 6 个项目,我只想要 4 个这样的东西:
[
"Jun 02 16:45:04 [steveh] [info] test1",
"Jun 02 16:45:12 [steveh] [info] test2",
"Jun 02 16:45:12 [steveh] [info] test3
test 3.1
test 3.2",
"Jun 02 16:45:16 [steveh] [info] test4"
]
我用 js 的 .match() 和 .split() 函数玩了一段时间,但没弄明白。
这里是 jsbin:http://jsbin.com/icufef/1/edit
【问题讨论】:
-
你从哪里得到这些数据?
-
实际上来自一个返回服务器日志的网络服务。我想在 javascript 中过滤该日志,因此我需要一个数组。但是对于测试,您可以将其作为多行字符串处理。
-
如果你知道你想要得到的确切格式,你可以尝试使用正则表达式来匹配该字符串而不是拆分。 Online demo
标签: javascript regex arrays split match