Home > Back-end >  Why I can't join all the string
Why I can't join all the string

Time:07-07

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.

CodePudding user response:

Try this

const text = `Test hello

Test1 hello

Test2 hello

Test3 hello`;

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

CodePudding user response:

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)

CodePudding user response:

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

  • Related