jQuery Convert Text to HTML List – $.stringToList

Sam Deering

This is a little jQuery utility function I wrote which simply converts text (ie – a long string) into a HTML list. It has a couple of settings for choosing conversion to Ordered List (OL) or Unordered List (UL). The delimiter for each item in the list is a full stop.

Before

text-to-list(1)

After

text-to-list(2)

jQuery.stringToList()

/*
 * $.stringToList
 * jQuery Function to convert a block of text into a html list.
 * @requires: full stops after each sentence to match list elements
 * @param: list type: ul or ol
 * Usage: $('#inclusions').stringToList('ul');
 * Author: Sam Deering
 */
$.fn.extend(
{
	stringToList: function(listType)
	{
		var sentenceRegex = /[a-z0-9,'‘- ]+/igm, htmlList = '< '+listType+'>';
		$.each($(this).html().match(sentenceRegex), function(i, v)
		{
			/* Remove blank elements */
			if (v &amp;&amp; (/[a-z0-9]+/igm.test(v)) &amp;&amp; v != 'strong') 
			{
				htmlList += '<li>' + v + '</li>';
			}
		});
		htmlList += '';
		$(this).html(htmlList);
	}
});

/* Convert text to html list */
$('#inclusions').stringToList('ul');

Custom Namespace Version

/*
 * $.stringToList - jQuery Function to convert a block of text into a html list.
 * @requires: full stops after each sentence to match list elements
 * @param: list type: ul or ol
 * Usage: FC.UTIL.stringToList($('#inclusions'),'ul');
 */
stringToList: function(textContainer,listType)
{
	var sentenceRegex = /[a-z0-9,'‘- ]+/igm, htmlList = '< '+listType+'>';
	$.each(textContainer.html().match(sentenceRegex), function(i, v)
	{
		/* Remove blank elements */
		if (v &amp;&amp; (/[a-z0-9]+/igm.test(v)) &amp;&amp; v != 'strong') 
		{
			htmlList += '<li>' + v + '</li>';
		}
	});
	htmlList += '';
	textContainer.html(htmlList);
}

/* Convert text to html list */
NAMESPACE.stringToList('#inclusions','ul');

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.