How to use replaceAll() method In Javascript
The replaceAll() method allows for replacing all instances of a substring or pattern in a string. This approach is straightforward and efficient for removing line breaks.
Example: In this example, the removeLineBreaksReplaceAll function uses replaceAll() to replace all occurrences of \n, \r, and their combination with an empty string.
// Input string
const str = `Hello
Welcome
to
w3wiki`;
// Display Input string
console.log(str);
// Function to remove line breaks using replaceAll method
function removeLineBreaksReplaceAll(str) {
return str.replaceAll('\r\n', '').replaceAll('\n', '').replaceAll('\r', '');
}
// Function call
const newString = removeLineBreaksReplaceAll(str);
console.log("New String:", newString);
Output
Hello Welcome to w3wiki New String: Hello Welcometow3wiki
How to remove all line breaks from a string using JavaScript?
Line breaks in strings vary from platform to platform, but the most common ones are the following:
- Windows: \r\n carriage return followed by a 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 a traditional programming loop and visiting every character one at a time. Another is using Regular Expressions.
Methods to Remove All Line Breaks from a String:
Table of Content
- Using JavaScript slice and stitch methods
- Using JavaScript RegEx with replace() method
- Using String.prototype.split() and Array.prototype.join()
- Using ES6 Template Literals with replace() method
- Using JavaScript replaceAll() method