Javascript Split Without Losing Character
I want to split certain text using JavaScript. The text looks like: 9:30 pm The user did action A. 10:30 pm Welcome, user John Doe. 11:30 am Messaged user John Doe Now, I want t
Solution 1:
Use a lookahead:
var split = journals.split(/(?=\b\d+:)/);
Solution 2:
Wouldn't it be easier to split on the newline?
var split = journals.split(/\n\n/);
EDIT
Try normalizing the string into a format that you can use:
/*
Non-normalized string
*/var str ="9:30 pm\nThe user did action A.10:30 pm\nWelcome, user John Doe.\n\n\n11:30 am\nMessaged user John Doe\n12:30 pm\nThe user did something else.";
/*
Normalizing into a specific format. TIMESTAMP\nDESCRIPTION\n\n.
Then removing extraneous leading \n\n
*/
str = str.replace(/\n*([0-9]{1,2}:[0-9]{2} (a|p)m)\n*/g, "\n\n$1\n").replace(/^\n+/, "");
var events = str.split(/\n\n/);
/*
The following should display an array of strings of the form:
TIMESTAMP\nDESCRIPTION
*/
console.log(events);
/*
Loop through events and split on single newline to get timestamp and description
*/for(var i =0; i < events.length; i++) {
var event = events[i];
var eventData = event.split(/\n/);
var time = eventData[0];
var description = eventData[1];
console.log(time, description);
}
Post a Comment for "Javascript Split Without Losing Character"