JavaScript RegExp \r Metacharacter

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

What You’ll Learn

The \r metacharacter matches a carriage return (CR) control character. It is a building block of line endings—especially Windows \r\n (CRLF)—and appears when parsing logs, CSV exports, and cross-platform text files.

01

CR char

\r

02

CRLF

\r\n

03

vs \n

LF alone

04

Normalize

\n

05

Split

Line breaks

06

ASCII 13

U+000D

Introduction

Text files store invisible characters to mark where one line ends and the next begins. On Windows, that is usually \r\n (carriage return + line feed). On Linux and macOS today, it is typically \n alone.

When your JavaScript code reads files from different systems, regex patterns with \r help you detect, split, or clean up those line-ending differences.

Understanding the \r Metacharacter

\r matches exactly one carriage return character. It does not match a visible letter or digit—it matches a control code embedded in the string.

JavaScript
const cr = "line one\rline two";

/\r/.test(cr);           // true
/\r/.test("line one\n"); // false (LF only, no CR)

"win\r\n".match(/\r\n/g); // ["\r\n"]

In regex literals, write /\r/. In a string for new RegExp(), escape the backslash: new RegExp("\\r").

💡
Beginner Tip

When normalizing line endings, handle \r\n before lone \r. Replace with /\r\n|\r/g so CRLF pairs become one newline, not two.

How to Use \r in JavaScript

Common tasks include detecting CR characters, splitting mixed line endings, and converting to a single format:

JavaScript
const raw = "a\r\nb\nc";

raw.includes("\r");                    // true
raw.split(/\r\n|\r|\n/);               // ["a", "b", "c"]
raw.replace(/\r\n|\r/g, "\n");         // "a\nb\nc" (Unix-style)

Use test() to check for CR presence, match() to find CRLF pairs, and replace() to normalize endings before processing.

📝 Syntax

JavaScript
/\r/              // single carriage return
/\r\n/            // Windows CRLF pair
/\r\n|\r|\n/      // any common line ending
/\r\n/g            // all CRLF pairs (global)

Common patterns

  • /\r\n/g — find all Windows-style line breaks.
  • /\r\n|\r/g — normalize CRLF and old Mac CR to LF.
  • /\r\n|\r|\n/ — split on any line-ending style.
  • /[^\r\n]+/g — match lines excluding break characters.

⚡ Quick Reference

GoalPattern
Match carriage return\r
Windows line break\r\n
Normalize to LFstr.replace(/\r\n|\r/g, "\n")
Split any line endingstr.split(/\r\n|\r|\n/)
Count CRLF pairs(str.match(/\r\n/g) || []).length
Unix line feed\n (not \r)

📋 \r vs \n vs \r\n

Three line-ending styles you will encounter in real text.

Carriage return
\r

CR · old Mac

Line feed
\n

LF · Unix/macOS

CRLF pair
\r\n

Windows

Normalize
\r\n|\r

→ \n

Examples Gallery

Open DevTools Console (F12) or use Try-it links. Examples cover detection, CRLF matching, normalization, line splitting, and cleanup.

📚 Getting Started

Detect carriage return characters in a string.

Example 1 — Test for Carriage Return

Check whether text contains a CR character.

JavaScript
const withCR = "hello\rworld";
const withLF = "hello\nworld";

console.log(/\r/.test(withCR));  // true
console.log(/\r/.test(withLF));  // false
console.log(/\n/.test(withLF));  // true
Try It Yourself

How It Works

\r and \n are different characters. A Unix-style string with only LF will not match /\r/.

📈 Practical Patterns

Match, normalize, split, and clean line endings.

Example 2 — Match Windows CRLF Pairs

Find every \r\n sequence in imported text.

JavaScript
const windowsText = "row1\r\nrow2\r\nrow3";

const breaks = windowsText.match(/\r\n/g);
console.log(breaks);              // ["\r\n", "\r\n"]
console.log(breaks.length);       // 2 line breaks
Try It Yourself

How It Works

Matching the two-character sequence \r\n targets Windows line endings as a unit, avoiding partial matches on lone CR or LF.

Example 3 — Normalize Line Endings to LF

Convert mixed CRLF and CR endings to Unix-style newlines.

JavaScript
const mixed = "line1\r\nline2\rline3\nline4";

const unix = mixed.replace(/\r\n|\r/g, "\n");
console.log(JSON.stringify(unix));
// "line1\nline2\nline3\nline4"
Try It Yourself

How It Works

The alternation tries \r\n first, then lone \r. Existing LF-only breaks stay unchanged.

Example 4 — Split Lines with Mixed Endings

Break text into rows regardless of line-ending style.

JavaScript
const blob = "alpha\r\nbeta\rgamma\ndelta";

const lines = blob.split(/\r\n|\r|\n/);
console.log(lines); // ["alpha", "beta", "gamma", "delta"]
Try It Yourself

How It Works

Listing CRLF before lone CR and LF ensures each break is consumed once, even in files pasted from different operating systems.

Example 5 — Strip Stray Carriage Returns

Remove invisible CR characters that break display or parsing.

JavaScript
const csvRow = "name,age\r";
const cleaned = csvRow.replace(/\r/g, "");

console.log(cleaned);           // "name,age"
console.log(/\r/.test(cleaned)); // false
Try It Yourself

How It Works

CSV and log files often carry a trailing CR. Stripping all \r characters cleans the value before comparison or storage.

🚀 Common Use Cases

  • File import — detect Windows CRLF in uploaded text files.
  • Log parsing — split log lines that mix CR and LF from different sources.
  • CSV cleanup — remove trailing carriage returns from cell values.
  • Cross-platform apps — normalize line endings before diffing or hashing.
  • HTTP headers — parse CRLF-delimited header blocks in raw messages.
  • Legacy Mac text — handle old CR-only line endings with /\r/g.

Important Considerations

  • Order in alternation — put \r\n before \r when normalizing, or CRLF becomes two replacements.
  • Invisible characters — CR is not visible in most editors; use JSON.stringify or char codes to debug.
  • Not the same as \n — patterns for one do not match the other.
  • String vs regex escaping"\\r" in strings vs /\r/ in literals require different backslash counts.
  • Modern macOS — current Mac files use LF; CR-only is mostly legacy but still appears in old data.

🧠 How \r Matches in Text

1

Scan string

The engine reads each character, including invisible control codes.

Input
2

Compare to \r

When the pattern expects \r, only ASCII 13 (U+000D) satisfies the match.

CR
3

Pair with \n

Patterns like \r\n match CR immediately followed by LF as one line break.

CRLF
4

Process lines

Split, replace, or validate once CR positions are identified.

📝 Notes

  • \r is carriage return; \n is line feed; Windows uses both as \r\n.
  • Normalize with .replace(/\r\n|\r/g, "\n") before comparing multiline strings.
  • Review \b word boundary for token matching in line-based text.
  • Next up: \d digit metacharacter.
  • String.prototype.split("\n") alone misses CR-only or CRLF text—use a regex split for robustness.
  • Char code check: str.charCodeAt(i) === 13 identifies CR without regex.

Browser & Runtime Support

The \r carriage-return escape is part of core JavaScript regular expression syntax.

Baseline · ES3+

RegExp \r

Supported in every browser and Node.js version. CRLF and normalization patterns behave consistently across runtimes.

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
\r Excellent

Bottom line: Safe everywhere. Use \r when parsing cross-platform text with mixed line endings.

Conclusion

The \r metacharacter matches carriage return control characters in strings. It is essential for handling Windows CRLF line endings, cleaning imported files, and splitting mixed-format text reliably.

Match \r\n for Windows breaks, normalize with /\r\n|\r/g, and always list CRLF before lone CR in alternations. Next, learn the \d digit metacharacter.

💡 Best Practices

✅ Do

  • Match \r\n for Windows line endings
  • Normalize with /\r\n|\r/g before processing
  • Split with /\r\n|\r|\n/ for mixed files
  • Use JSON.stringify to debug invisible CR chars
  • Handle CRLF first in alternation patterns

❌ Don’t

  • Assume \n alone matches Windows breaks
  • Replace \r before handling \r\n pairs
  • Confuse string "\\r" escaping with regex literal /\r/
  • Ignore trailing CR in CSV or form data
  • Display raw CR characters without normalizing for users

Key Takeaways

Knowledge Unlocked

Five things to remember about RegExp \r

Handle carriage return and CRLF line endings in JavaScript.

5
Core concepts
💻 02

CRLF

\r\n

Windows
🔄 03

Normalize

→ LF

Pattern
04

Split

Any EOL

Lines
05

Order

CRLF first

Pitfall

❓ Frequently Asked Questions

\r matches the carriage return control character (CR, Unicode U+000D, ASCII 13). It moves the cursor to the start of the line in classic teletype systems and appears in some line-ending formats.
\r is carriage return (CR). \n is line feed (LF). Unix and Linux use \n alone for new lines. Windows traditionally uses both together as \r\n (CRLF).
Windows files often use CRLF (\r\n). Matching only \r can leave stray \n characters, and matching only \n can miss the \r. For full Windows line breaks, use /\r\n/g.
In a regex literal like /\r/, the backslash is part of the pattern. In a normal string passed to new RegExp(), write "\\r" so JavaScript produces the regex escape \r.
Replace all CRLF and lone CR with LF: text.replace(/\r\n|\r/g, "\n"). That converts Windows and old Mac endings to Unix-style newlines.
The \r escape is core regex syntax since ES3. It works in every browser and Node.js version.
Did you know?

The names “carriage return” and “line feed” come from typewriters and teletypes: CR moved the print head to the start of the line, and LF advanced the paper. Windows kept both characters in software line endings; Unix simplified to LF only.

Continue to \d digit metacharacter

Learn how \d matches any digit character in a string.

\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