Search code examples
javascriptphpjqueryinsertword-count

How can I insert a <hr> after the first <p> or <br> following every 5,000 characters of some text?


I have some very long passages. I want to break them up for easier reading. I want to divide them by adding a <hr> tag for every 5,000 characters. But I also don't want to divide the text in the middle of a paragraph. So I want to add the <hr> tag just after the first <p> or <br> of every 5,000 characters. The 'text' has HTML formatting already so we can find the <p> or <br> directly within the text.

I can do it with PHP in the back end or JS/jQuery in the front-end, whichever is the better way.

I'm a novice and I'm completely stuck. I don't know how to achieve this. Hope you can help. Thank you very much!


Solution

  • Here is a solution in jQuery. A jsFiddle is available.

    In the sample, I am splitting at 100 characters so we can see the effect. The code is as follows:

    $(function () {
        var counter = 0;
        $("p").each(function (i, element) {
            counter += $(element).text().length;
            if (counter > 100) {
                counter = 0;
                $(element).append("<hr/>");
            }
        });
    });
    

    The high level of the algorithm is to keep a counter of text sizes for each paragraph and when it exceeds the threshold, add a horizontal line and reset the counter.