jQuery: turning text into an HTML list

jQuery: turning text into an HTML list

How to turn a text string into an HTML list using jQuery.

Turning text into an HTML list is not so difficult with jQuery. All we have to do is to create the right plugin for this purpose. In this article we'll see how to take a text string and turn it into an ordered HTML list using jQuery and regular expressions.

We start with the following markup:

<div id="test">1. Lorem ipsum dolor 2. Est ideo autem 3. Ibam forte sicut meus est mos</div>

Items in text are separated by a progressive number followed by a period. In this case, our regular expressions pattern is obviously /\d\./g. We use the global flag because we want to make sure that all the text string will be parsed.

Here's our jQuery plugin:

(function($) {
    $.fn.listify = function(options) {
        var that = this;
        var settings = {
            pattern: /\d\./g,
            target: $('#output')
        };
        options = $.extend(settings, options);

        return that.each(function() {

            var obj = $(that);
            var text = obj.text();
            var parts = text.split(options.pattern);
            var html = '<ol>';

            for (var i = 1; i < parts.length; i++) {

                var part = parts[i];
                html += '<li>' + part + '</li>';

            }

            html += '</ol>';

            options.target.html(html);



        });
    };
})(jQuery);

The split() method also accepts a regular expression to create an array from a string. All we have to do is to loop through the returned array and build an HTML string.

Example:

$('#test').listify();​

You can see the demo below.

Demo

Live demo