How to use RegEx with replace() method In Javascript
Regular Expression:
This method uses regular expressions to detect and replace newlines in the string. It is fed into replace function along with a 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
/\r\n|\n|\r/gm
As you can see that this regex has covered all cases separated by the | operator. This can be reduced to
/[\r\n]+/gm
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.
Example: This example shows the removal of all line breaks from the given string.
// Input string
str = "Hello \nWelcome\nto\nw3wiki";
//Display Input string
console.log(str);
// Regular Expression
function remove_linebreaks(str) {
return str.replace(/[\r\n]+/gm, " ");
}
function removeNewLines() {
let sample_str = str;
// For printing time taken on console.
console.log("nwe String: "+remove_linebreaks(str));
}
removeNewLines();
Output
Hello Welcome to w3wiki nwe String: Hello Welcome to w3wiki
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