JavaScript RegExp \n Metacharacter
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.
let regex = /\n/;
let str = "Hello\nWorld";
console.log(regex.test(str));
Output
true
The pattern \n detects the presence of a newline character (\n) in the string.
Syntax:
/\n/
- \n: Matches a newline character in the input string.
Key Points
- Matches only newline characters (\n).
- Commonly used in parsing or validating multi-line text.
- Does not match other whitespace characters like spaces ( ) or tabs (\t).
Real-World Examples
1. Detecting a Newline
let regex = /\n/;
let str = "Line 1\nLine 2";
if (regex.test(str)) {
console.log("Newline detected!");
} else {
console.log("No newline found.");
}
Output
Newline detected!
2. Splitting Text by Newlines
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
let str = "Hello\nWorld";
let replaced = str.replace(/\n/g, " ");
console.log(replaced);
Output
Hello World
The \n is replaced with a space, converting the string into a single line.
4. Counting Newlines in a String
let str = "Line 1\nLine 2\nLine 3";
let regex = /\n/g;
let count = (str.match(regex) || []).length;
console.log(count);
Output
2
This counts the number of newline characters in the string.
5. Matching Specific Patterns Across Lines
let regex = /Hello\nWorld/;
let str = "Hello\nWorld";
console.log(regex.test(str));
Output
true
Here, the regex explicitly matches the sequence Hello followed by a newline and World.
Common Patterns Using \n
- Match Strings with Newlines:
/Line 1\nLine 2/
- Replace Newlines with Spaces:
str.replace(/\n/g, " ");
- Count Newlines:
(str.match(/\n/g) || []).length;
- Split by Newlines:
str.split(/\n/);
- Remove All Newlines:
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?
- Multi-Line Parsing: Essential for processing text files, logs, or user inputs with line breaks.
- Efficient Line Handling: Enables developers to count, split, or manipulate strings based on newlines.
- Cross-Platform Compatibility: Use in combination with \r to handle newline variations between systems.
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:
- JavaScript RegExp Complete Reference
- JavaScript Cheat Sheet-A Basic guide to JavaScript
- JavaScript Tutorial