views:

54

answers:

2

In the script, sometimes a newline is added in the beginning of the text field (am using a textArea in adobe flex 3), and later on that newline might need to be removed (after other text has been added). I was wondering how to check if there is a newline at the beginning of the text field and then how to remove it. Thanks in advance.

+3  A: 

How about

private function lTrimTextArea(ta:TextArea) {
  ta.text = ta.text.replace(/^\n*/,'');
}
Robusto
Thanks, that looks promising. I only want to replace the \n newline at the beginning of the text field though. There are other newlines later in the text that I want to keep. Is there a way to restrict the replace to just the first line (or even just the first instance of \n)?
Steven
Just took a look at the replace function more closely and it does the trick as far as removing the first \n. But i only want to replace the \n if it is at the beginning of the text. Do you know how I would check if there is a \n at the beginning of the text field? Thanks
Steven
What I have shown you does that already. The caret (^) at the beginning of the regexp expression means only remove newlines from the very start of the text.
Robusto
Sometimes, the \n will come after a few characters so might be at index 3 for example. The script would know what index it would be at if it were there, is there a way to check at a particular index if there is a \n? Thanks for the help.
Steven
After a few alphanumeric characters or is it going to be white-space characters?
Robusto
they would be white space characters although if there is a way for alphanumeric characters it would be really useful to know how to do that as well
Steven
@Steven: the regular expression you're looking for would be `/^[\n\s\t]*/` for whitespace. The brackets indicate grouping and the star means 0 or more. You can specify an alphanumeric range with `[a-zA-Z0-9]` or `\w`, but if you stick any of those in there you run the rest of replacing some actual text. Google "regular expressions" and find a primer that will help you. Meanwhile, if this has answered your question, be a good citizen and click the check mark to accept the answer.
Robusto
thanks! very helpful
Steven
A: 

To remove all line breaks from the start of a string, regardless of whether they are Windows (CRLF) or UNIX (LF only) line breaks, use:

ta.text = ta.text.replace(/^[\r\n]+/,'');

You should use + in the regex instead of * so that the regex only makes a replacement if there is actually a line break at the start of the string. If you use ^\n* as Robusto suggested the regex will find a zero-length match at the start of the string if the string does not start with a line break, and replace that with nothing. Replacing nothing with nothing is a waste of CPU cycles. It may not matter in this situation, but avoiding unintended zero-length matches is a very good habit when working with regular expressions. In other situations they will bite you.

Jan Goyvaerts