I have some arbitrary body text in a container. I don't control it so I don't know its structure. But something like this:
<div id='content-area'>
<h1>Heading</h1>
<p>A paragraph or two</p>
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
</div>
That is just a simple example for illustration, in reality it could contain many more items and nested things like tables.
I want to pull out all the text and do some processing on the words used. I'm using the following jQuery to get the text.
$('#content-area').text()
// HeadingA paragraph or twoitem 1item 2
The problem is that there are no spaces between each tagged item. The documentation says:
Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.
And all my searches seem to pull up results for removing white space. Is there a way pull out all the text and keep space between elements? Needs to happen in-browser so javascript-ish methods.
To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split('').
Add space below a line or paragraph of text To add extra space below a line or paragraph of text, or push text down lower on the page once, you can use the <br> tag.
The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.
In case of unknown nested structure you can add blanks to every element
https://jsfiddle.net/3y2yLexv/1/
$( "*" ).each(function( index ) {
$( this ).append(' ');
});
var str = $('#content-area').text();
//Of course you have to trim duplicated blank spaces.
str = str.replace(/\s\s+/g, ' ');
$('#new').text(str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With