Josh Bullough
Josh Bullough

Reputation: 54

How do I split text by every other line?

Or in other words by every two lines? Right now i only seem to be able to split by every line.

the list would be something like this copied into the text area:

Style:
CGV7
Fabric:
95% Polyester, 5% Elastane
Source:
Imported
Guarantee:
Lifetime Warranty

this is the result I want

Style: CGV7
Fabric: 95% Polyester, 5% Elastane
Source: Imported
Guarantee: Lifetime Warranty

here is my code:

  <textarea id="tables" name="" cols="78" rows="10" onchange="splitIt()"> 
  </textarea>

  function splitIt(){
     var items = [];
     var tablevalues = document.getElementById("tables").value;
     var splitItems =tablevalues.split(/\n/);
       items.push(splitItems);
       console.log(items);
 }   

Upvotes: 0

Views: 1129

Answers (2)

Tran Loc
Tran Loc

Reputation: 451

I hope that this is what you are looking for:

str.replace(/[\r\n]/g, " ")
   .split(" ")
   .filter((x) => x.trim())
   .join("\n")

Updated, this might be short and cool :)

a.split(/:\n/).join(":")

Upvotes: 0

Pranay Tripathi
Pranay Tripathi

Reputation: 1882

  let p = text.split('\n');
  let results = '';

  p.forEach((x, index) => {
    if (index%2 !== 0) {
      results = results + x + '\n';
    }
    else {
      results = results +x;
    }
  });
  console.log(results);

You can achieve this by splitting the whole string on \n and then you can add it back on every odd element concat.

Upvotes: 1

Related Questions