Click to See Complete Forum and Search --> : Truncating text with return characters


AndrewMB
April 18th, 2008, 07:33 AM
I am trying to truncate the text in Javascript from within <textarea></textarea> tags (returned in IE by the innerHTML property) to a fixed length. However the user may press the return key during text entry, which generates a CR/LF character pair. Any attempt to manipulate this string (for example using substr, substring or slice) truncates the text at the first CR/LF.

I can replace the CR/LF with something else, but again can find no way to reintroduce these characters into the string.

Is there any way to return the first n characters of the string preserving any embedded CR/LF?

Andrew

Alsvha
April 18th, 2008, 08:38 AM
If I'm reading you right, you want a specific length of the string the user have entered, but the length count should exclude linebreaks (CR/LF)
Is this correctly understood?

PeejAvery
April 18th, 2008, 09:29 AM
So as to preserve the original, why not create a temporary variable equal to the original? Then you can string replace the temporary to remove \n and shorten it with substr().

AndrewMB
April 18th, 2008, 12:47 PM
To clarify - what I want to do is to truncate the original to a fixed number of characters, and place this original back into the textarea. In other words, I want to give the user a maximum number of characters he can enter in the textarea, and any excess characters will be cut off as they are typed.

However I have now found a solution. It seems the problem was because I was setting the innerHTML property of the textarea, and this doesn't like CR/LF characters. Using the value property instead seems to resolve it (and is cross-browser compatible).

Thank you.