Js高级字符串拆分

时间:2017-08-19 11:01:30

标签: javascript string split

我有一个来自.txt文件的长字符串,其中包含我要分割的几个句子和日期。

语法就像这样

01-01-15: Here is some text
02-01-15: Here is some other text
05-06-17: Here is some new text
06-06-17: Here is some text
taking up 
several lines
07-06-17: And so on

由于某些句子占用了几行,我无法使用text.split("\n") - 但我可以做什么呢? 所有句子都以xx-xx-xx开头,其中x是数字。

2 个答案:

答案 0 :(得分:5)

您可以通过使用先行模式搜索每个逻辑单元的开始日期来拆分行。



var data = '01-01-15: Here is some text\
02-01-15: Here is some other text\
05-06-17: Here is some new text\
06-06-17: Here is some text\
taking up \
several lines\
07-06-17: And so on';


console.log(data.split(/(?=\d\d-\d\d-\d\d:)/));




答案 1 :(得分:1)

我刚刚遇到了一种使用JS的字符串模板拆分字符串的巧妙方法

let str = "Justin"
console.log(str.split``) 
// ["J", "u", "s", "t", "i", "n"]