0
const dummyText = `First line
                              Second line
                                                       Third line


    Last Line`

const expectedOutput = `First Line
Second line
Third line
Last Line`

dummyText.replace(/ +?/g, ''), this regex currently replacing all the spaces in between words. I need to remove spaces start and end of the string, have to preserve newline

Below output currently I'm getting

FirstLine Secondline Thirdline LastLine

I need output like expectedOutput variable value

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
Arun M
  • 1
  • 1

2 Answers2

0

Without a fancy regular expression it can be a split, trim, filter, and join

const dummyText = `First line
                          Second line
                                                   Third line


Last Line`

const result = dummyText
  .split(/\n/)   // split on new lines
  .map(x => x.trim()) //clean up the new lines
  .filter(Boolean)  // remove empty lines
  .join('\n')  // join it back together
console.log(result);
epascarello
  • 195,511
  • 20
  • 184
  • 225
-2

It's possible to use .trim() to remove all spaces

const greeting = '   Hello world!   ';

console.log(greeting);
// expected output: "   Hello world!   ";

console.log(greeting.trim());
// expected output: "Hello world!";