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-n-metacharacter/ below:

JavaScript RegExp \n Metacharacter - GeeksforGeeks

JavaScript RegExp \n Metacharacter

Last Updated : 11 Jul, 2025

The \n metacharacter in JavaScript regular expressions matches a newline character. It is used to identify line breaks in strings, enabling developers to process multi-line text effectively.

JavaScript
let regex = /\n/;
let str = "Hello\nWorld";
console.log(regex.test(str));

The pattern \n detects the presence of a newline character (\n) in the string.

Syntax:
/\n/
Key Points Real-World Examples 1. Detecting a Newline JavaScript
let regex = /\n/;
let str = "Line 1\nLine 2";
if (regex.test(str)) {
    console.log("Newline detected!");
} else {
    console.log("No newline found.");
}
2. Splitting Text by Newlines JavaScript
let str = "First line\nSecond line\nThird line";
let lines = str.split(/\n/);
console.log(lines);

Output
[ 'First line', 'Second line', 'Third line' ]

This splits a multi-line string into an array of individual lines.

3. Replacing Newlines JavaScript
let str = "Hello\nWorld";
let replaced = str.replace(/\n/g, " ");
console.log(replaced);

The \n is replaced with a space, converting the string into a single line.

4. Counting Newlines in a String JavaScript
let str = "Line 1\nLine 2\nLine 3";
let regex = /\n/g;
let count = (str.match(regex) || []).length;
console.log(count);

This counts the number of newline characters in the string.

5. Matching Specific Patterns Across Lines JavaScript
let regex = /Hello\nWorld/;
let str = "Hello\nWorld";
console.log(regex.test(str));

Here, the regex explicitly matches the sequence Hello followed by a newline and World.

Common Patterns Using \n
/Line 1\nLine 2/
str.replace(/\n/g, " ");
(str.match(/\n/g) || []).length;
str.split(/\n/);
str.replace(/\n/g, "");
Limitations

Matches Only Newlines: It does not match other types of line terminators like \r. Use \r?\n for cross-platform newline matching.

Why Use \n Metacharacter? Conclusion

The \n metacharacter is a fundamental tool in regex for handling text spanning multiple lines. Its simplicity and effectiveness make it indispensable for string processing.

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