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');
    Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

    Free Guide:

    How to Choose the Right Charting Library for Your Application

    How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.


    Learn JavaScript for free!
    Free course: Introduction to JavaScript

    Yours when you take up a free 14-day SitePoint Premium trial.