We can make use of the replace() method to replace all the newlines from a String. Let us take a look at it by an example.
Example 1:
const egStr = 'Hello \
and \
Welcome \
to \
Code2care!';
const strWithoutNewLines = egStr.replace(/[\r\n]/gm, '');
console.log(strWithoutNewLines);
Let's see another example where we have newline characters (EOL) within our string.
Example 2:
const egStr = "Today \n is a good \n day!\n";
const strWithoutNewLines = egStr.replace(/[\r\n]/gm, '');
console.log(strWithoutNewLines);
Note: As the newline character can be a \n, \r or a \r\n, it is better to have a Regex that matches and removes all of such characters.
EOL Character | Description | Usage |
---|---|---|
\n | Newline character (Line Feed) | Used in Unix and Linux Systems. |
\r | Carriage Return | Used in older Macintosh Systems. |
\r\n | Carriage Return + Newline (CRLF) | Used in Windows and DOS Environments. |

-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to JavaScript,
- Get Current time in GMT/UTC using JavaScript
- How to get current URL Location using Javascript HTML
- Excel Fix: SECURITY RISK Microsoft has blocked macros from running because the source of this file is untrusted.
- Convert Javascript object to JSON String example
- Fix: ReferenceError: require is not defined in ES module scope [Node]
- [JavaScript] Remove all Newlines From String
- JavaScript : Get url protocol HTTP, HTTPS, FILE or FTP
- Fix: Error: error:0308010C:digital envelope routines::unsupported NodeJs/Vue/React
- Pure JavaScript Digital Clock Widget to get GMT/UTC Time Now
- Fix: npm vs code eacces permission denied unlink /usr/local/bin/code
- Power of Print Statements in JavaScript: A Comprehensive Guide
- [javaScript] Convert text case to lowercase
- JavaScript: Count Words in a String
- JavaScript date in yyyy-MM-dd format
- How to send email from JavaScript HTML using mailto
- How to get UTC (GMT) time using JavaScript
- JavaScript: Generate Random Numbers between 1 and 3
- How to get query string in JavaScript HTML location.search
- Fix: Uncaught ReferenceError: exit is not defined - Node.js REPL
- Detect if Cookies are enabled using JavaScript
- Submit html form on dropdown menu value selection or change using javascript
- Send Extra Data with Ajax Get or Post Request
- Loading previous page using html button using JavaScript
- 10 ways to Convert String to a Number in JavaScript
- JavaScript: Check if variable is a number
More Posts:
- How to reset Mac Password using Terminal - MacOS
- Installing Microsoft Edge on M1/M2 Mac - Microsoft
- macOS say command text to speech using various voices and languages - MacOS
- [Fix] Microsoft AADSTS900561: The endpoint only accepts POST requests. Received a GET request. - Microsoft
- How to FTP using Mac Terminal - MacOS
- How to Open and Use Windows Terminal App - Windows
- PowerShell: Check if File Exists - Powershell
- How to configure PDF iFilter for SharePoint - SharePoint