1

I have a issue, I'm using JS. Let's say I have this text separated by paragraphs:

Test hello

Test1 hello

Test2 hello

Test3 hello

and then I want to join all the paragraphs next to each other like this: Test hello Test1 hello Test2 hello Test3 hello, so I did this:

<pre>
var x = string.trim();
var xArr = x.match(/^\n|\S+/gm);
var xJoin = xArr.join(" ");
</pre>

but it continue as before with paragraphs, I try with string.replace() too. After the x.match(/^\n|\S+/gm) it brings me the array like this:

<pre>
[, ,
Test, hello

, ,
Test1, hello

, ,
Test2, hello

, ,
Test3, hello

, ,
 

]
</pre>

So this seemed a bit strange to me, could it be that it is not really separated by line breaks? Any idea how to put the strings next to each other? Thanks.

  • Possible duplicate https://stackoverflow.com/questions/10805125/how-to-remove-all-line-breaks-from-a-string – Robin Webb Jul 06 '22 at 14:38

3 Answers3

2

Try this

const text = `Test hello

Test1 hello

Test2 hello

Test3 hello`;

console.log(text.split('\n').filter(t => !!t).join(" "));
Haris Bouchlis
  • 2,366
  • 1
  • 20
  • 35
2

You need to fix some minor issues in your code

  1. Need to use replace if you want to replace new line with space
  2. Need to remove ^ ( this start of string ) from you pattern

let str = `Test hello

Test1 hello

Test2 hello

Test3 hello`


var x = str.trim();
var xArr = x.replace(/\n|\r|\r\n/gm, ' ');

console.log(xArr)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

Is your paragraph in an html element? If so you can just use this:

const textElement = document.getElementById("text");
console.log(textElement.innerText);
<div id="text">
  Test hello

  Test1 hello

  Test2 hello

  Test3 hello
</div>

Or, put it in an html element created from your javascript before using the above method.

Otherwise you can try this regex? text.replace(/(\r\n|\n|\r)/gm, "");

Mulaga
  • 103
  • 8