[javascript] How to remove all line breaks from a string

I have a text in a textarea and I read it out using the .value attribute.

Now I would like to remove all linebreaks (the character that is produced when you press Enter) from my text now using .replace with a regular expression, but how do I indicate a linebreak in a regex?

If that is not possible, is there another way?

This question is related to javascript regex string

The answer is


The simplest solution would be:

let str = '\t\n\r this  \n \t   \r  is \r a   \n test \t  \r \n';
str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"

.replace() with /\s+/g regexp is changing all groups of white-spaces characters to a single space in the whole string then we .trim() the result to remove all exceeding white-spaces before and after the text.

Are considered as white-spaces characters:
[ \f\n\r\t\v?\u00a0\u1680?\u2000?-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]


var str = "bar\r\nbaz\nfoo";

str.replace(/[\r\n]/g, '');

>> "barbazfoo"

If it happens that you don't need this htm characte &nbsp shile using str.replace(/(\r\n|\n|\r)/gm, "") you can use this str.split('\n').join('');

cheers


How you'd find a line break varies between operating system encodings. Windows would be \r\n, but Linux just uses \n and Apple uses \r.

I found this in JavaScript line breaks:

someText = someText.replace(/(\r\n|\n|\r)/gm, "");

That should remove all kinds of line breaks.


To remove new line chars use this:

yourString.replace(/\r?\n?/g, '')

Then you can trim your string to remove leading and trailing spaces:

yourString.trim()

On mac, just use \n in regexp to match linebreaks. So the code will be string.replace(/\n/g, ''), ps: the g followed means match all instead of just the first.

On windows, it will be \r\n.


This will replace the line break by empty space.

someText = someText.replace(/(\r\n|\n|\r)/gm,"");

Read more on this article.


A linebreak in regex is \n, so your script would be

var test = 'this\nis\na\ntest\nwith\newlines';
console.log(test.replace(/\n/g, ' '));

I am adding my answer, it is just an addon to the above, as for me I tried all the /n options and it didn't work, I saw my text is comming from server with double slash so I used this:

var fixedText = yourString.replace(/(\r\n|\n|\r|\\n)/gm, '');

If you want to remove all control characters, including CR and LF, you can use this:

myString.replace(/[^\x20-\x7E]/gmi, "")

It will remove all non-printable characters. This are all characters NOT within the ASCII HEX space 0x20-0x7E. Feel free to modify the HEX range as needed.


_x000D_
_x000D_
var str = " \n this is a string \n \n \n"_x000D_
_x000D_
console.log(str);_x000D_
console.log(str.trim());
_x000D_
_x000D_
_x000D_

String.trim() removes whitespace from the beginning and end of strings... including newlines.

const myString = "   \n \n\n Hey! \n I'm a string!!!         \n\n";
const trimmedString = myString.trim();

console.log(trimmedString);
// outputs: "Hey! \n I'm a string!!!"

Here's an example fiddle: http://jsfiddle.net/BLs8u/

NOTE! it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.


Try the following code. It works on all platforms.

var break_for_winDOS = 'test\r\nwith\r\nline\r\nbreaks';
var break_for_linux = 'test\nwith\nline\nbreaks';
var break_for_older_mac = 'test\rwith\rline\rbreaks';

break_for_winDOS.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'

break_for_linux.replace(/(\r?\n|\r)/gm, ' ');
//output
'test with line breaks'

break_for_older_mac.replace(/(\r?\n|\r)/gm, ' ');
// Output
'test with line breaks'

Simple we can remove new line by using text.replace(/\n/g, " ")

_x000D_
_x000D_
const text = 'Students next year\n GO \n For Trip \n';
console.log("Original : ", text);

var removed_new_line = text.replace(/\n/g, " ");
console.log("New : ", removed_new_line);
_x000D_
_x000D_
_x000D_


The answer provided by PointedEars is everything most of us need. But by following Mathias Bynens's answer, I went on a Wikipedia trip and found this: https://en.wikipedia.org/wiki/Newline.

The following is a drop-in function that implements everything the above Wiki page considers "new line" at the time of this answer.

If something doesn't fit your case, just remove it. Also, if you're looking for performance this might not be it, but for a quick tool that does the job in any case, this should be useful.

// replaces all "new line" characters contained in `someString` with the given `replacementString`
const replaceNewLineChars = ((someString, replacementString = ``) => { // defaults to just removing
  const LF = `\u{000a}`; // Line Feed (\n)
  const VT = `\u{000b}`; // Vertical Tab
  const FF = `\u{000c}`; // Form Feed
  const CR = `\u{000d}`; // Carriage Return (\r)
  const CRLF = `${CR}${LF}`; // (\r\n)
  const NEL = `\u{0085}`; // Next Line
  const LS = `\u{2028}`; // Line Separator
  const PS = `\u{2029}`; // Paragraph Separator
  const lineTerminators = [LF, VT, FF, CR, CRLF, NEL, LS, PS]; // all Unicode `lineTerminators`
  let finalString = someString.normalize(`NFD`); // better safe than sorry? Or is it?
  for (let lineTerminator of lineTerminators) {
    if (finalString.includes(lineTerminator)) { // check if the string contains the current `lineTerminator`
      let regex = new RegExp(lineTerminator.normalize(`NFD`), `gu`); // create the `regex` for the current `lineTerminator`
      finalString = finalString.replace(regex, replacementString); // perform the replacement
    };
  };
  return finalString.normalize(`NFC`); // return the `finalString` (without any Unicode `lineTerminators`)
});

You can use \n in a regex for newlines, and \r for carriage returns.

var str2 = str.replace(/\n|\r/g, "");

Different operating systems use different line endings, with varying mixtures of \n and \r. This regex will replace them all.


USE THIS FUNCTION BELOW AND MAKE YOUR LIFE EASY

The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.

function remove_linebreaks( var message ) {
    return message.replace( /[\r\n]+/gm, "" );
}

In the above expression, g and m are for global and multiline flags


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript