user370306
user370306

Reputation:

Remove the last "\n" from a textarea

How to remove the last "\n" from a textarea?

Upvotes: 57

Views: 50766

Answers (6)

Jue
Jue

Reputation: 39

Tried to use trim under debug console but it does not work:

text
'Add to Cart\n'
text.trim()
'Add to Cart\n'

Upvotes: 0

Yurii Kosiak
Yurii Kosiak

Reputation: 410

You can do it this way (.*[^\n])\n* Result: https://regex101.com/r/lWKzFy/1

Upvotes: 0

aarti
aarti

Reputation: 2865

Only remove the last newline characters (\n):

verses1 = "1\n222\n"
verses1.replace(/\n$/, "")
// "1\n222"

verses2 = "1\n222\n\n"
verses2.replace(/\n$/, "")
// "1\n222\n"

Only all the last newlines (\n):

verses = "1\n222\n\n"
verses.replace(/\n+$/, "")
// "1\n222"

https://regexr.com/4uu1r

Upvotes: 81

Brian D
Brian D

Reputation: 2110

I personally like lodash for trimming newlines from strings. https://lodash.com/

_.trim(myString);

Upvotes: 2

Ben Taliadoros
Ben Taliadoros

Reputation: 9331

$.trim() should do the trick!

It trims whitespace and newline characters from the beginning and ending of the specified string.

Upvotes: 6

John Boker
John Boker

Reputation: 83699

from http://en.wikipedia.org/wiki/Trim_%28programming%29

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, "");
};

That will add a trim function to string variables that will remove whitespace from the beginning and end of a string.

With this you can do stuff like:

var mystr = "this is my string   "; // including newlines
mystr = mystr.trim();

Upvotes: 13

Related Questions