Keri
Keri

Reputation: 375

textContent() without spaces from formatting text

I have an html like this:

<div id="info">
    <h1> My title </h1?
    <div>
        <p> Here is a text and one paragraph </p>
        <p> Another paragraph </p>
    </div>
</div>

I would like to take the inner text without the tags from the whole div#info. So I use this:

document.querySelector('div#info').textContent

And the results have some spaces like this:

"
    My title




Here is a text and one paragraph
Another Paragraph




"

Any idea if there is any command which could give the result to so one line like this:

 "My title Here is a text and one paragraph Another Paragraph"

I tries also the innerText() but it has again spaces.

Upvotes: 6

Views: 25107

Answers (3)

Rob M.
Rob M.

Reputation: 36521

You need a regex to remove all of the newlines and excess whitespace:

.replace(/[\n\r]+|[\s]{2,}/g, ' ')

Then you can .trim() the result of that call:

console.log(
  document.querySelector('div#info')
          .textContent
          .replace(/[\n\r]+|[\s]{2,}/g, ' ').trim()
)
<div id="info">
    <h1> My title </h1>
    <div>
        <p> Here is a text and one paragraph </p>
        <p> Another paragraph </p>
    </div>
</div>

Upvotes: 32

Rajesh
Rajesh

Reputation: 24945

Since you have multiple spaces in your text, you can use string.replace to replace multiple spaces by single space.

You should also use string.trim() to exclude trailing and leading spaces.

var text = document.querySelector('div#info').textContent
console.log(text.replace(/\s+/g, " ").trim())
<div id="info">
    <h1> My title </h1>
    <div>
        <p> Here is a text and one paragraph </p>
        <p> Another paragraph </p>
    </div>
</div>

Upvotes: 8

Sagar V
Sagar V

Reputation: 12478

You can use a regex to remove all spaces.

console.log(document.querySelector('div#info').textContent.replace(/\s{2,}/g,' '));
<div id="info">
    <h1> My title </h1?
    <div>
        <p> Here is a text and one paragraph </p>
        <p> Another paragraph </p>
    </div>
</div>

Upvotes: 4

Related Questions