Categories
JavaScript Answers

How to Remove All Line Breaks From a JavaScript String?

Spread the love

String.prototype.replace

We can call the replace method with a regex to search for all line breaks in a string and replace them all with empty strings to remove the line breaks.

For instance, we can write:

const trimmed = 'abc\r\ndef'.replace(/(\r\n|\n|\r)/gm, "");
console.log(trimmed)

to remove all the line breaks.

\r and \n are the patterns for the line breaks.

g lets us search the whole string for all instances of line break characters.

Therefore trimmed is 'abcdef' .

We can also use the control code character equivalent in place of \r and \n by writing:

const trimmed = 'abc\r\ndef'.replace(/\[^\x20-\x7E\]/gmi, "")
console.log(trimmed)

\x20 is equivalent to \r .

And \x7E is equivalent to \n .

String.prototype.trim

The trim method lets us remove all line break characters from the start and end of a string.

For instance, we can write:

const trimmed = 'abc\r\n'.trim()
console.log(trimmed)

Then trimmed is 'abc' .

String.prototype.trimStart

The trimStart method lets us remove all line break characters from the start of a string.

For instance, we can write:

const trimmed = '\r\nabc'.trimStart()
console.log(trimmed)

Then trimmed is 'abc' .

String.prototype.trimEnd

The trimEnd method lets us remove all line break characters from the end of a string.

For instance, we can write:

const trimmed = 'abc\r\n'.trimEnd()
console.log(trimmed)

Then trimmed is 'abc' .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *