Categories
JavaScript Answers

How to split string in JavaScript by line breaks?

Spread the love

Sometimes, we want to split string in JavaScript by line breaks.

In this article, we’ll look at how to split string in JavaScript by line breaks.

How to split string in JavaScript by line breaks?

To split string in JavaScript by line breaks, we call the string split method with a regex.

For instance, we write

const array = str.split(/\r?\n/);

to call str.split with a regex that matches \r\n or \n to split str into an array with either as separators.

Conclusion

To split string in JavaScript by line breaks, we call the string split method with a regex.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *