Steven
Steven

Reputation: 35

How to check for and remove a newline (\n) in the first line of a text field in actionscript?

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.

Upvotes: 1

Views: 6138

Answers (4)

Zze
Zze

Reputation: 18805

If you want to simply disable the ability to create a carriage return / new line, then all you need to do is disable multiline for that TextField...

(exampleTextField as TextField).multiline = false;

This will still trigger KEY_DOWN and KEY_UP events, however will not append the text with the carriage return.

Upvotes: 0

Dileep Kumar Kottakota
Dileep Kumar Kottakota

Reputation: 127

If you particularly want to check first character here is solution:

if(ta.text.charAt(0) == "\n" || ta.text.charAt(0) == "\r")
{
     ta.text.slice(1,ta.text.length-1);
}

slice method will slice that first character and gives your text from second character.

Upvotes: 0

Jan Goyvaerts
Jan Goyvaerts

Reputation: 21999

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.

Upvotes: 1

Robusto
Robusto

Reputation: 31883

How about

private function lTrimTextArea(ta:TextArea) {
  ta.text = ta.text.replace(/^\n*/,'');
}

Upvotes: 4

Related Questions