0

i want to trim 3 letter on each newline . but when i do split it only split the first line the other newline already gone. Kindly help. Thank you.

This is the code:

var mytext = '(1x) test0, (2x) test1, (3x) test2';

var formattedString = mytext.replace(/,/g, '\n');

console.log("FORMATTED STRING", formattedString)

const output = formattedString
    .split('', 4)
    .reduce((o, c) => (o.length === 4 ? `${o}${c}` : `${o}${c}`), '')

console.log("SPLIT", output)

Can access the code here:

https://jsfiddle.net/mqnkx2uc/14/

I want the output like this: "(1x) \n (2x) \n (3x)"

TechDev
  • 415
  • 5
  • 18

1 Answers1

2

I'd use a regex to start by matching a ), then match non-( characters, and replace with )\n:

var mytext = '(1x) test0, (2x) test1, (3x) test2';
console.log(
  mytext.replace(
    /\)[^\(]+/g,
    ')\n'
  )
  .trim()
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320