1

I have an output stream for a program which contains list of available printers and I want to turn it into array.

This is my stdout:


OneNote                        

Microsoft XPS Document Writer  

Microsoft Print to PDF         

Fax                            



And I am seeking for a solution that will give me:

['OneNote', 'Microsoft XPS Document Writer', 'Microsoft Print to PDF', 'Fax']

I tried stdout.split('\n'), but it became

[
 'OneNote                        \r\r', 
 'Microsoft XPS Document Writer  \r\r', 
 'Microsoft Print to PDF         \r\r', 
 'Fax                            \r\r',
 '\r\r',
 ''
]

Then I tried stdout.split('\r\r\n') and it turns into

[
 'OneNote                        ', 
 'Microsoft XPS Document Writer  ', 
 'Microsoft Print to PDF         ', 
 'Fax                            ',
 '',
 ''
]

Now I can removes whitespace from ends of the strings stdout.split('\r\r\n').map(printer => printer.trim()) but I still need to filter out last two empty strings, so I was wondering is there any better/elegant way to solve the problem?

stdout.split('\r\r\n')
  .map(printer => printer.trim())
  .filter(printer => Boolean(printer.length))
1
  • 1
    trim() the string before splitting it Commented Jun 8, 2019 at 18:32

1 Answer 1

1

You can use a regular expression -

input.trim().split(/\s*[\r\n]+\s*/)

See it working in this complete program below -

const input = 
`
OneNote                        

Microsoft XPS Document Writer  

Microsoft Print to PDF         

Fax                            
`

const output =
  input.trim().split(/\s*[\r\n]+\s*/)
  
console.log(output)
// [
//   "OneNote",
//   "Microsoft XPS Document Writer",
//   "Microsoft Print to PDF",
//   "Fax"
// ]

The regular expression targets any carriage returns \r and/or line feeds \n surrounded by optional whitespace. It can be understood as -

  • \s* - zero-or-more whitespace, followed by
  • [\r\n]+ - one-or-more \r or \n, followed by
  • \s* - zero-or-more whitespace
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.