I need to create a bit of Javascript that can search inputted HTML from a text box and ignore all the tags to automatically word wrap at a set number like say 70 and add a <br> tag.
I also need to find all the ascii like © and – and count that as one space not 5 or 4 spaces.
So the code would take:
<b>Hello</b> Here is some code that I would like to wrap. Lets pretend this goes on for over 70 spaces.
Output would be:
<b>Hello</b> Here is some code that I would like to wrap. Lets pretend <br>
this goes on for over 70 spaces.
Is this possible? How would I begin? Is there already a tool for this?
By the way CSS is out of the question to use.
While the combination of the phrases “regular expression” and “parse HTML” usually causes entire universes to crumble, your use case seems simplistic enough that it could work, but the fact that you want to preserve HTML formatting after wrapping makes it much easier to just work on a space-delimited sequence. Here is a very rough approximation of what you’d like to do:
which results in
Note that the HTML tags (
b,em,strong) are preserved, it’s just that Markdown doesn’t show them.Basically, the input string is split into words at each space, which is naïve and likely to cause trouble, but it’s a start. Then, the length of each word is calculated after anything resembling an HTML tag or entity has been removed. Then it’s a simple matter of iterating over each word, keeping a running tally of the column we’re on; once we’ve struck 70, we pop the aggregated words into the output string and reset. Again, it’s very rough, but it should suffice for most basic HTML.