I have some data that I am trying to process with javascript.
DATA:
A. Category one
1. item one
2. item two
B. Category two
3. item three
4. item four
C. Category three
5. item five
6. item six
DESIRED OUTPUT:
[{
"Category one":["item one", "item two"],
"Category two":["item three", "item four"],
"Category three":["item five", "item six"]
}]
Is there a library that will help me with text parsing in javascript?
THIS IS AS FAR AS I GOT:
function parseFormat(str) {
var arr = [];
str.split('\n').forEach(function (line) {
var obj = {};
line.split('.').forEach(function (item) {
if (isNaN(item)) {
// ??
} else {
}
});
return ?;
});
}
Help? Thanks
Here is the complete function. Please have a look at the code below.
Function to parse the string
function parseFormat(strArg) { var category, output = {}, // Output str = strArg.trim(); // Remove unwanted space before processing str.split('\n').forEach(function(line) { var item = line.split('.'); if (item[0].match(/\d/)) { // Match a decimal number // Remove unwanted space & push output[category].push(item[1].trim()); } else if (item[0].match(/\D/)) { // Match UPPERCASE alphabet // Remove unwanted space category = item[1].trim(); output[category] = [] } }); return output; }Input string
// ES6 Template Strings to define multiline string var str = ` A. Category one 1. item one 2. item two B. Category two 3. item three 4. item four C. Category three 5. item five 6. item six `;Function call
// Final output Array var finalOutput = []; // Parse input string var parseStr = parseFormat(str); finalOutput.push(parseStr); // Desired JSON output console.log(JSON.stringify(finalOutput));
You can look at the Browser Console for the desired JSON output.
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With