How to Split a String by Newline in JavaScript
To split a string by newline in JavaScript, you can use the split()
method combined with a regular expression string.split(/\r?\n/)
this matches newline characters. Here’s an example:
let string = "Hello\nWorld\nThis is JavaScript";
let lines = string.split(/\r?\n/); // Splits by both Windows and Unix newlines
console.log(lines);
// Output: [ 'Hello', 'World', 'This is JavaScript' ]
This code splits the string by newline characters (\n
or \r\n
) and returns an array with each line as an element.
(/\r?\n/) is a regular expression that matches either \r\n (Windows-style) or \n (Unix-style) newline characters.
Follow the steps below to split a string by newline in JavaScript.
Steps:
- Prepare the string: Create a string that contains newline characters. You can use the escape sequence
\n
to represent the newline. - Use the
split()
method: Use thesplit()
method with the regular expressionstring.split(/\r?\n/)
this matches newline characters to split the string into an array of lines. - Log the result: Output the result to the console using
console.log()
to verify the string is correctly split.