Remove line breaks from start and end of string

String.trim() does in fact remove newlines (and all other whitespace). Maybe it didn't used to? It definitely does at the time of writing. From the linked documentation (emphasis added):

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).


If you want to trim all newlines plus other potential whitespace, you can use the following:

return str.trim();

If you want to only trim newlines, you can use a solution that targets newlines specifically.


Try this:

str = str.replace(/^\s+|\s+$/g, '');

jsFiddle here.