➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
JavaScript Replace Carriage Return and Newline | This tutorial will show you how to eliminate line breaks from Javascript. Want to make a “flat string” in Javascript by eliminating all line breaks? In fact, there are a few approaches to take:
1. String.replace(/\r?\n|\r/, ""
);
2. String.replace(/\r/g, ""
).replace(/\n/g, ""
);
The fundamentals should be covered, but if you want more specific examples, keep reading!
JavaScript Replace Carriage Return and Newline Using replace()
Everyone on the Internet, including me, seems to endorse this approach the most. Replace(/r?n|r/, “”) will be used to eliminate all line breaks because regular expressions are a huge bag of worms.
// String
var str = "JavaScript\r\ is a \r\n very popular\n language\r";
console.log("Original:", str);
// Strip first line break
var nobreak = str.replace(/\r?\n|\r/, "");
console.log("Output: ", nobreak);
Output:-
is a al: JavaScript
very popular
language
Output: JavaScript is a
very popular
language
// String
var str = "JavaScript\r\ is a \r\n very popular\n language\r";
console.log("Original:", str);
// Strip all line break
var nobreak = str.replace(/\r?\n|\r/g, "");
console.log("Output: ", nobreak);
Output:-
is a al: JavaScript
very popular
language
Output: JavaScript is a very popular language
An alternative method for removing line breaks is to replace all ‘\r’ and ‘\n’ characters with an empty string.
var str = "JavaScript\r\ is a \r\nvery popular\n language\r";
console.log("Original:", str);
str = str.replace(/\r/g, "").replace(/\n/g, "");
console.log("Output: ", str);
Output:-
is a al: JavaScript
very popular
language
Output: JavaScript is a very popular language
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!