Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Why I can't join all the string

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Try this

const text = `Test hello

Test1 hello

Test2 hello

Test3 hello`;

console.log(text.split('\n').filter(t => !!t).join(" "));

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report

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, "");

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!