Split String by New Line
To split a string by new line character in JavaScript, call split() method on the given string and pass new line delimiter string as argument in the method call.
The expression to split a string str
by new line delimiter is
</>
Copy
str.split('\n');
Example
In the following example, we take a multiline string in str
, split the string by new line delimiter '\n'
, and display the splits array in pre#output.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
var str = `apple
banana
cherry`;
var values = str.split('\n');
for(index = 0; index < values.length; index++) {
document.getElementById('output').innerHTML += index + ' - ' + values[index] + '\n';
}
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned how to split the given string by new line character using String.split() method, with example program.