A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-regexp-r-metacharacter/ below:

JavaScript RegExp \r Metacharacter - GeeksforGeeks

JavaScript RegExp \r Metacharacter

Last Updated : 11 Jul, 2025

The \r metacharacter in JavaScript regular expressions matches a carriage return character. A carriage return is a special control character (\r) with the ASCII code 13, often used to represent the end of a line in text files created on older operating systems (e.g., Windows uses \r\n for line breaks).

JavaScript
let regex = /\r/g;
let str = "Hello\rWorld";
let matches = str.match(regex);
console.log(matches); 

The pattern \r matches the carriage return character in the string.

Syntax:
/\r/

Matches a single carriage return character (\r).

Key Points Real-World Examples 1. Detecting Carriage Return JavaScript
let regex = /\r/;
let str = "Line1\rLine2";
if (regex.test(str)) {
    console.log("Carriage return found.");
} else {
    console.log("No carriage return found.");
}

Output
Carriage return found.

Here, the \r metacharacter detects the presence of a carriage return in the string.

2. Replacing Carriage Returns JavaScript
let regex = /\r/g;
let str = "Hello\rWorld";
let result = str.replace(regex, "");
console.log(result); 

Using \r with replace(), you can remove carriage return characters from a string.

3. Handling Windows-Style Newlines JavaScript
let regex = /\r\n/g;
let str = "Line1\r\nLine2";
let result = str.replace(regex, "\n");
console.log(result); 

The pattern \r\n matches Windows-style line endings and converts them to a Unix-style newline (\n).

4. Splitting Text with Carriage Returns JavaScript
let regex = /\r/;
let str = "Line1\rLine2\rLine3";
let parts = str.split(regex);
console.log(parts); 

Output
[ 'Line1', 'Line2', 'Line3' ]

Here, \r is used to split the string into parts wherever a carriage return is found.

5. Normalizing Line Endings JavaScript
let regex = /\r/g;
let str = "Hello\r\nWorld\r";
let normalized = str.replace(regex, "");
console.log(normalized); 

This example removes all carriage returns, leaving only Unix-style line endings.

Common Patterns Using \r
/\r\n/
str.replace(/\r/g, "")
/(\r\n|\r|\n)/g
str.split(/\r/)
Why Use \r? Conclusion

The \r metacharacter is essential for working with text files or handling input strings containing Windows-style line endings.

Recommended Links:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4