Last active
September 23, 2015 09:46
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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