Line breaks in strings vary from platform to platform, but the most common ones are the following:
- Windows: \r\n carriage return followed by newline character.
- Linux: \n just a newline character.
- Older Macs: \r just a carriage return character.
There are two methods to accomplish this task. One of the ways is by using traditional programming loop and visiting every character one at a time. Another is using Regular Expressions.
The slice and stitch method: It is the basic way to realize the solution to this problem. Visit each character of the string and slice them in such a way that it removes the newline and carriage return characters.
All this code snippet does it just copy all the characters that are not “newline” or “carriage return” to another variable. However, there are a lot of overheads in this solution and therefore not an optimal way to remove newlines.
Regular Expression: This method uses regular expressions to detect and replace newlines in the string. It is fed into replace function along with string to replace with, which in our case is an empty string.
String.replace( regex / substr, replace with )
The regular expression to cover all types of newlines is
As you can see that this regex has covered all cases separated by | operator. This can be reduced to
where g and m are for global and multiline flags.
The best part is that this method performed almost 10 times better than the previous one.
- Before Clicking on the button:
- After Clicking on the button:
- How to remove line breaks from the string in PHP?
- How to prevent line breaks in the list of items using CSS?
- How to add line breaks to an HTML textarea?
- How to Read a File Line by Line to String in Golang?
- How to read a file line by line using node.js ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.