How to remove the last "/n" from a textarea?
+2
A:
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();
John Boker
2010-06-21 12:45:45
If all @lam3r4370 wants to do is replace one trailing `\n` character, replace `/^\s+|\s+$/g` above with `/\n$/`. Also, if you're planning on distributing this code or putting it where it is likely to share space with JS from other users, I'd recommend you just create a generic function `trim` rather than using `String.prototype`. Though it's very common practice, you can cause trouble for others by adding methods to core JS objects.
Andrew
2010-06-21 12:58:51
@Andrew , your way changes the cursor position.@John ,your's - moves the text on the begginning of the textarea.
lam3r4370
2010-06-21 13:27:33
Oh. Are you trying to remove the trailing line break on a textarea that the user is updating?
Andrew
2010-06-21 14:59:33
I guess it's obvious you are trying to update the text area without changing where the user's cursor is. Check out [this SO post](http://stackoverflow.com/questions/263743/how-to-get-cursor-position-in-textarea) about getting the cursor position. It's a messy process that requires some browser-specific hacks. Read the cursor position; remove the trailing white space; set the cursor position to what it was before. Are you sure you need to update the text area while the user is still in it? I'd be surprised if you couldn't leave the textarea as is and trim the text before you use it.
Andrew
2010-06-21 15:14:01
@Andrew ,I am trying to learn javascript and decided to make a online code editor only for my own use(to "upgrade" my knowledge).I think that is the answer of your question.
lam3r4370
2010-06-21 16:28:03
@Andrew the first code in the topic only gets the cursor position ,I think?
lam3r4370
2010-06-21 16:29:38