jQuery Convert Text to HTML List – $.stringToList
Share
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
After
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 = '';
$.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 = '';
$.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');