iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🪓

Properly Splitting Text into Lines in JavaScript

に公開

This is code used when hard-coding a list of strings.
It converts a multi-line template literal (heredoc) into a String array.

Ignoring leading and trailing empty lines

const lines = `
a
b
`
  .trim()
  .split('\n')

// [ 'a', 'b' ]

Note
Note that it returns [''] when the text is empty or contains only newlines.

Removing all empty lines

const lines = `
a

b
`
  .split('\n')
  .filter(Boolean)
// [ 'a', 'b' ]

Removing leading and trailing empty lines and supporting 0 lines

const text = `
a
b
`
const lines = text === '' ? [] : text.trim().split('\n')

When converted into a function:

const toLines = (text) => (text === '' ? [] : text.trim().split('\n'))

toLines(`
a

b
`)
// [ 'a', '', 'b' ]

toLines(`
`)
// [ '' ]
GitHubで編集を提案

Discussion