JavaScript RegExp \n Metacharacter

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Line feed

What You’ll Learn

The \n metacharacter matches a line feed (LF)—the newline character that separates lines in Unix-style text. It is essential for splitting paragraphs, counting lines, parsing logs, and working with multiline patterns.

01

LF char

\n

02

New line

Unix/macOS

03

Split

Lines

04

vs \r\n

Windows

05

m flag

Multiline

06

In \s

Whitespace

Introduction

When you press Enter in a text area, JavaScript usually inserts a line feed character. That invisible code is what \n matches in a regular expression.

Newlines appear everywhere: multiline user input, server logs, CSV exports, and template strings. Regex with \n helps you split, count, validate, and transform line-based data.

Understanding the \n Metacharacter

\n matches exactly one line feed character. It is not the two-character sequence backslash-n in the source text—it is the single control code at that position in the string.

JavaScript
const text = "line one\nline two";

/\n/.test(text);         // true
/\n/.test("single");     // false

text.split("\n");        // ["line one", "line two"]

Line feed is part of the \s whitespace class. On Windows, a visible line break is often stored as \r\n, but many web APIs and modern files use \n alone.

💡
Beginner Tip

To split lines reliably across platforms, use /\r\n|\r|\n/ instead of only /\n/ when the source may be Windows or old Mac text.

How to Use \n in JavaScript

Common workflows include splitting, counting, replacing, and line-aware matching with the multiline flag:

JavaScript
const poem = "roses\nviolets\nsugar";

poem.split(/\n/);                    // 3 lines
(poem.match(/\n/g) || []).length;    // 2 newlines

"hello\nworld".replace(/\n/g, " ");  // "hello world"

/^done$/m.test("start\ndone\nnext"); // true (m flag)

Use split(/\n/) for line arrays, match(/\n/g) to count breaks, and the m flag when ^ and $ should apply per line.

📝 Syntax

JavaScript
/\n/              // single line feed
/\n+/             // one or more newlines
/\r\n|\n/         // Windows or Unix line break
/^line$/m         // whole line match (multiline)
/\s/              // whitespace (includes \n)

Common patterns

  • /\n/g — find every newline in text.
  • str.split(/\n/) — break into an array of lines.
  • /\r\n|\r|\n/g — split on any line-ending style.
  • /^# .+/gm — match comment lines in multiline text.

⚡ Quick Reference

GoalPattern / Code
Match newline\n
String literal LF"\n"
Split into linesstr.split(/\n/)
Count newlines(str.match(/\n/g) || []).length
Any line ending\r\n|\r|\n
Per-line anchors/pattern/m

📋 \n vs \r vs \r\n vs \f

Four line-related control characters and endings.

Line feed
\n

Unix LF

Carriage return
\r

CR only

CRLF
\r\n

Windows

Form feed
\f

Page break

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover detection, splitting, counting, multiline anchors, and cross-platform line endings.

📚 Getting Started

Detect line feed characters in a string.

Example 1 — Test for a Newline Character

Return true when the text contains at least one line break.

JavaScript
console.log(/\n/.test("one line"));       // false
console.log(/\n/.test("two\nlines"));    // true
console.log(/\n/.test("a\r\nb"));        // true (contains \n in CRLF)
Try It Yourself

How It Works

A single-line string has no LF character. Windows CRLF still contains \n as the second half of the pair, so /\n/ matches.

📈 Practical Patterns

Split, count, anchor per line, and handle mixed endings.

Example 2 — Split Text into Lines

Break a multiline string into an array of rows.

JavaScript
const log = "INFO boot\nWARN slow\nERROR fail";

const lines = log.split(/\n/);
console.log(lines);
// ["INFO boot", "WARN slow", "ERROR fail"]

console.log(lines[1]); // "WARN slow"
Try It Yourself

How It Works

split(/\n/) cuts at each line feed, producing one array element per line without the delimiter characters.

Example 3 — Count Newlines in Text

Find how many line breaks appear in a block of text.

JavaScript
const essay = "Intro\nBody\nConclusion";

const breaks = essay.match(/\n/g);
console.log(breaks);              // ["\n", "\n"]
console.log(breaks.length);       // 2

console.log(essay.split(/\n/).length); // 3 lines
Try It Yourself

How It Works

Two newlines create three lines. Counting \n matches gives line breaks; counting split segments gives total lines.

Example 4 — Match a Whole Line with the m Flag

Use multiline mode so ^ and $ work per line.

JavaScript
const block = "todo: buy milk\ndone: walk dog\n todo: sleep";

console.log(/^done:/m.test(block));    // true
console.log(/^done:/.test(block));     // false (no ^ at string start)

console.log(/^todo:/gm.test(block));    // true (two todo lines)
Try It Yourself

How It Works

The m flag treats each line as its own segment for ^ and $, powered by newline boundaries in the string.

Example 5 — Split Mixed Line Endings

Handle Unix, Windows, and legacy Mac breaks in one pattern.

JavaScript
const mixed = "a\r\nb\nc\rd";

const lines = mixed.split(/\r\n|\r|\n/);
console.log(lines); // ["a", "b", "c", "d"]

const normalized = mixed.replace(/\r\n|\r/g, "\n");
console.log(JSON.stringify(normalized)); // "a\nb\nc\nd"
Try It Yourself

How It Works

Listing \r\n first prevents splitting CRLF into two breaks. Normalizing converts everything to Unix-style \n.

🚀 Common Use Cases

  • Log parsing — split server output into one object per line.
  • Form validation — reject input that contains embedded newlines when single-line is required.
  • CSV / config files — process line-oriented records with regex per row.
  • Textarea processing — count lines in user-submitted essays or code.
  • Markdown / comments — match lines starting with # using the m flag.
  • Normalization — convert mixed line endings to consistent \n.

Important Considerations

  • Platform endings — Windows files may use \r\n; do not assume \n alone for all uploads.
  • Dot metacharacter — by default . does not match \n; use the s (dotAll) flag to include newlines.
  • Visible vs invisible — newlines are control chars; use JSON.stringify to inspect them in DevTools.
  • Trim empty linessplit(/\n/) may leave trailing empty strings if text ends with a newline.
  • String vs regexsplit("\n") and split(/\n/) behave the same for simple LF splits.

🧠 How \n Matches in Text

1

Scan position

The engine reads the next character in the input string.

Read
2

Compare to LF

\n succeeds only when the character is ASCII 10 (line feed).

Match
3

Line boundary

With the m flag, ^ and $ treat \n as a line edge.

Multiline
4

Process lines

Split, count, replace, or validate line-based data.

📝 Notes

  • \n is line feed; Windows often uses \r\n together.
  • Review \r carriage return for CR and CRLF details.
  • Next up: \D non-digit metacharacter.
  • String.prototype.split("\n") is fine when you know endings are LF-only.
  • Template literals use real newlines: `line1\nline2` contains \n characters.
  • Char code check: str.charCodeAt(i) === 10 identifies LF without regex.

Browser & Runtime Support

The \n line-feed escape is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp \n

Supported in every browser and Node.js version. Multiline (m) flag for per-line anchors is also universal.

99% Universal syntax
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
\n Excellent

Bottom line: Safe everywhere. Use \n for line-based parsing and the m flag for per-line ^ and $.

Conclusion

The \n metacharacter matches line feed newlines—the foundation of multiline text processing in JavaScript. Split lines, count breaks, and pair with the m flag for per-line pattern matching.

Remember cross-platform line endings and consider \r\n|\r|\n when files come from mixed sources. Next, learn the \D metacharacter for matching non-digits.

💡 Best Practices

✅ Do

  • Use /\r\n|\r|\n/ for cross-platform splits
  • Add m when ^ and $ apply per line
  • Count with match(/\n/g) for line-break totals
  • Normalize to \n before storing text
  • Trim trailing empty lines after split if needed

❌ Don’t

  • Assume all files use LF-only newlines
  • Confuse \n with the two-char sequence \\n in data
  • Expect . to match newlines without the s flag
  • Forget CRLF when counting lines in Windows text
  • Split on \n only when CRLF pairs would leave stray \r

Key Takeaways

Knowledge Unlocked

Five things to remember about RegExp \n

Match and process newline characters in JavaScript.

5
Core concepts
02

Split

Lines

Pattern
📈 03

m flag

Per line

Anchors
💻 04

CRLF

Windows

Compare
🔢 05

In \s

Whitespace

Class

❓ Frequently Asked Questions

\n matches the line feed (LF) control character (Unicode U+000A, ASCII 10). It represents a new line in Unix, Linux, and modern macOS text.
In JavaScript source code, "\n" in a string literal creates a newline character. In regex, /\n/ matches that same LF character wherever it appears in text.
\n is a single line feed. Windows often stores \r\n (carriage return + line feed) as one line break. Match Windows endings with /\r\n/; match Unix-style lines with /\n/.
Yes. Line feed is included in the \s whitespace class along with space, tab, form feed, and carriage return.
The m flag makes ^ and $ match at line boundaries (before/after \n) instead of only at the start/end of the entire string.
The \n escape is core regex syntax since ES3. It works in every browser and Node.js version.
Did you know?

JavaScript template literals preserve real newline characters when you break lines inside backticks. That means a multiline template string already contains \n characters—no escape sequence required in the source.

Continue to \D non-digit metacharacter

Learn how \D matches any character that is not a digit.

\D tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful