我有一些数据正在尝试使用 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"]
}]
有没有一个库可以帮助我用 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 ?;
});
}
帮助?谢谢
这是完整的function
。请看下面的代码。
解析字符串的函数
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;
}
输入字符串
// 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
`;
函数调用
// Final output Array
var finalOutput = [];
// Parse input string
var parseStr = parseFormat(str);
finalOutput.push(parseStr);
// Desired JSON output
console.log(JSON.stringify(finalOutput));
您可以查看浏览器控制台以获取所需的 JSON 输出。
希望能帮助到你!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)