JavaScript
Article

jQuery Convert Text to HTML List – $.stringToList

By 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 && (/[a-z0-9]+/igm.test(v)) && v != 'strong') 
			{
				htmlList += '
  • ' + v + '
  • '; } }); 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 && (/[a-z0-9]+/igm.test(v)) && v != 'strong') 
    		{
    			htmlList += '
  • ' + v + '
  • '; } }); htmlList += ''; textContainer.html(htmlList); } /* Convert text to html list */ NAMESPACE.stringToList('#inclusions','ul');

    Free Guide:

    7 Habits of Successful CTOs

    "What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

    Recommended
    Sponsors
    Because We Like You
    Free Ebooks!

    Grab SitePoint's top 10 web dev and design ebooks, completely free!

    Get the latest in JavaScript, once a week, for free.