Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript function to convert a string into an object incliding an array of items for each linebreak in the string. It removes bulletpoints and numbers from formatting.
function parseTextToItems(value) {
var text = value.trim();
// Remove multiple linebreak.
var match = /\r\n/.test(text);
if (match == -1) {
//windows line breaks
text = text.replace(/\r\n+/g, "\r\n");
} else {
//unix line breaks
text = text.replace(/\r/g, "\n");
text = text.replace(/\n+/g, "\n");
}
// Remove last empty bullet/number list item
text = text.replace(/\n$/, "")
text = text.replace(/\n\d\.$/, "")
text = text.replace(/\n\d\)$/, "")
text = text.replace(/\n[IVXivx]+\.$/, "")
text = text.replace(/\n[IVXivx]+\)$/, "")
text = text.replace(/\n[A-Za-z]+\)$/, "")
text = text.replace(/\n[A-Za-z]+\.$/, "")
// Check if text contains linebreaks
var isMultiple = /\n/g.test(text);
// Check if the list is a numbered list
var isNumbered =
/\d\.\s+/.test(text) ||
/\d\)\s/.test(text) ||
/[IVXivx]+\.\s+/.test(text);
// Remove bullet/number list formating
text = text.replace(/^\s+/gm, "")
text = text.replace(/^\d\.\s+/gm, "")
text = text.replace(/^\d\)\s+/gm, "")
text = text.replace(/^[IVXivx]+\.\s+/gm, "")
text = text.replace(/^[IVXivx]+\)\s+/gm, "")
text = text.replace(/^[A-Za-z]+\)\s+/gm, "")
text = text.replace(/^[A-Za-z]+\.\s+/gm, "")
// Remove empty lines
text = text.replace(/^\s*\n/gm, "");
// Split items into an array
var items = text.trim().split("\n");
// Count number of items
var totalItems = (items ? items.length : 0);
return {
totalItems: totalItems,
isNumbered: isNumbered,
isMultiple: isMultiple,
items: items
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment