【问题标题】:How to split a string input that uses the same separator for items and their values如何拆分对项目及其值使用相同分隔符的字符串输入
【发布时间】:2022-01-08 11:03:44
【问题描述】:

我有一个文本消息,我必须在其中根据时间格式化值,然后将其保存到 excel 文件中。我尝试了溢出和加入功能,但它有新行,所以它不起作用。有没有办法在 javascript 中做到这一点?

我的文字:

16:15 test1 success
17:05 test4 success
17:40 test4234 down
18:25 test322 success
19:10 test423 success
20:20 test123 down
21:05 test454 success
21:40 test4 success
22:40 test145 success
23:35 test1123 down
00:35 testxx success
20:20 test123 down
14:20 test126 down
13:20 test177 success

mycode.js

const data =
'16:15 EURJPY-OTC PUT
17:05 USDJPY-OTC PUT
17:40 EURJPY-OTC PUT
18:25 EURGBP-OTC CALL
19:10 USDJPY-OTC PUT
20:20 USDJPY-OTC PUT
21:05 NZDUSD-OTC CALL
21:40 EURUSD-OTC CALL
22:40 USDJPY-OTC PUT
23:35 USDJPY-OTC PUT
00:35 NZDUSD-OTC CALL';
console.log(data.split('').join(','),'datataaaaa')

【问题讨论】:

  • 我想我在这里误解了一些东西,您的文本数据样本也已经包含换行符。那么您可能收到的 1000 个“条目”数据是否有换行符?这会是 1000 行的单个字符串(每行末尾有一个换行符)吗?
  • 数据不会有换行。为了检查我添加的拆分功能,它不起作用。如果它令人困惑,我可以删除。
  • 嗯,是的,请更改文本数据示例以显示实际数据中条目之间的分隔符。
  • 我已经删除了新行。谢谢 :)
  • 我会在它们之间添加空格,格式类似于“time testname teststatus”

标签: javascript node.js arrays json object


【解决方案1】:

假设接收到的数据具有相同的分隔符来分隔条目和分隔(每个条目的)字段,您仍然可以可靠地解析输入,因为您知道每个条目总是有 3 个字段。

function parseEntries(data) {
  const entries = []

  const tokens = data.split(' ') // space is the delimiter 
  for (let i = 2; i < tokens.length; i += 3) {
    entries.push({
      time: tokens[i - 2],
      name: tokens[i - 1],
      status: tokens[i]
    })
  }

  return entries
}

const data =
  '16:15 EURJPY-OTC PUT 17:05 USDJPY-OTC PUT 17:40 EURJPY-OTC PUT 18:25 EURGBP-OTC CALL'

const entries = parseEntries(data)
console.log(entries)

entries.forEach(e => {
  // do whatever you need here with each entry
  // e.time
  // e.name
  // e.status
})

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多