Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to jQuery text() that includes spaces between elements?

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.

like image 596
Rothrock Avatar asked Sep 17 '15 16:09

Rothrock


People also ask

How do you put a space between two words in jquery?

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('').

How do you put a space between two strings in HTML?

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.

How do I remove extra space between words in jquery?

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.


1 Answers

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);
like image 110
Trike Avatar answered Oct 05 '22 08:10

Trike