Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda