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');
    Sam Deering
    Meet the author
    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.

    Recommended

    Learn Coding Online
    Learn Web Development

    Start learning web development and design for free with SitePoint Premium!

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