iTranslated by AI

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

How to remove the first n lines of a string in JavaScript

に公開

Code 1

A method using Array#slice.

const removeHeads = (s, n) => s.split('\n').slice(n).join('\n')
const removeHeads = (s, n) => s.split('\n').slice(n).join('\n')

removeHeads(text, 1)
// 'line2\nline3\nline4'
removeHeads(text, 2)
// 'line3\nline4'
removeHeads(text, 3)
// 'line4'
removeHeads(text, 4)
// ''
removeHeads(text, 5)
// ''

Code 2

Code 1 is fine, but this is a method using regular expressions that I first thought of.
I wasn't sure if it would be faster, but (it cannot be used when the passed n is greater than the number of lines).
It was slow. Repl.it - regex-vs-slice

const removeHeads = (s, n) => s.replace(new RegExp(".*\n".repeat(n))
GitHubで編集を提案

Discussion