textContent() without spaces from formatting text

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

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

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

console.log( document.querySelector('div#info') .textContent .replace(/[\n\r]+|[\s]/g, ' ').trim() )
 

My title

Here is a text and one paragraph

Another paragraph

answered Mar 21, 2017 at 7:47 36.4k 6 6 gold badges 54 54 silver badges 51 51 bronze badges

This approach will have 2 spaces between title and Here as you are only replacing new line characters and OP has extra spaces in text.

Commented Mar 21, 2017 at 7:50 @Rajesh That is not what I'm seeing in the output from Run code snippet Commented Mar 21, 2017 at 7:52 Please try using HTML instead of inline text. JSFiddle Commented Mar 21, 2017 at 7:54 Thanks @Rajesh, I've updated my answer and checked in JSFiddle - appreciate the help! Commented Mar 21, 2017 at 8:02 [\n\r] is also \s , so the pipe is redundant. A simple .replace(/\s+/g, ' ') should suffice. Commented Apr 4, 2023 at 9:16

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

My title

Here is a text and one paragraph

Another paragraph