Skip to content

Instantly share code, notes, and snippets.

@frejnorling
Last active September 23, 2015 09:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frejnorling/14442b50a599b4d7989e to your computer and use it in GitHub Desktop.
Save frejnorling/14442b50a599b4d7989e to your computer and use it in GitHub Desktop.
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