How to trim a string in JavaScript preserving new lines and carriage returns?
let str = " rA string with carriage returnsn ";
The built-in trim() function removes the new line characters.
// Returns "A string with carriage returns"
str.trim()
How to remove only leading and trailing spaces ?
3
Answers
Use
String.replace
with a regexp that matches spaces at the end of the string.Use
String.replace
with a regexp that matches spaces at the start and the end of the string.Here’s an alternative solution that doesn’t use RegEx:
which yields:
as expected.
Disadvantage: Less concise, more error prone. Advantage: More predictable performance (many JavaScript RegEx engines are still implemented inefficiently).
Alternatively, rather than removing the parts you don’t want using a RegEx, you could also capture the parts you do want:
Explanation:
^...$
: start to end*
: zero or more leading spaces(.*?)
the actual body – note the lazy*?
*
: zero or more trailing spaces)Disadvantage: This is slower than AKX’s answer and my "plain JS" answer.