Categories
JavaScript Answers

How to Remove All Line Breaks From a JavaScript String?

Spread the love

Sometimes, we need to remove all line breaks from a string in the JavaScript app.

In this article, we’ll look at how to remove all line breaks from a JavaScript string.

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' .

Conclusion

We can use string replace method to remove all newline characters from a string.

And we can use the trim , trimStart or trimEnd methods to remove newline characters from the start and end, start or end of the string respectively.

Leave a Reply

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