Escape and Unescape / Handling Carriage Returns in Textareas
Ever notice how the URLs of search engines and other sites are cluttered with % symbols and other numbers? This is known as URI encoding, which is simply % signs followed by nonalphanumeric characters that have been converted to their hexadecimal values. The reason for this encoding is to allow multiple word strings mingled with nonalphanumeric characters to be sent together as a single string, which will either be stored in a database or decoded and reconstructed later on.
JavaScript can encode a regular string via the Escape Method, and decode an encoded string via the Unescape Method.
Here is a string.
<a href="javascript:alert( escape('Here is a string') )">Here is the string encoded.</a>
Here%20is%20a%20string.
<a href="javascript:alert( unescape('Here%20is%20a%20string') )">Here is the string decoded.</a>
The unescape method can be used for decoding an encoded URL string for display in a document or some other type of reconstruction, while the escape method can be used to encode a string being sent to a CGI script. These methods also come in handy for tasks which involve printing to and from a textarea, and removing or preserving textarea carriage returns. While you could use the "\r\n" string combination for printing to a textarea instead of escaping, employing an escape - replace - unescape technique ensures a cross-browser, cross-platform solution, and keeps your scripts consistent regardless of the task at hand.
Printing from a textarea
Task: print a textarea string to a new window, which will require the preservation of all carriage returns in the string. The process begins by escaping the entire string. Then the replace method is used to replace each instance of the hex version of the return character (%0D) and/or new line character (%0A), depending on the operating system, with an HTML break tag.
Enter text broken up with carriage returns
Here is the function:
function escapeVal(textarea,replaceWith){ textarea is reference to that object, replaceWith is string that will replace the encoded return
textarea.value = escape(textarea.value) encode textarea string's carriage returns
for(i=0; i<textarea.value.length; i++){ loop through string, replacing carriage return encoding with HTML break tag
if(textarea.value.indexOf("%0D%0A") > -1){ Windows encodes returns as \r\n hex
textarea.value=textarea.value.replace("%0D%0A",replaceWith)
}
else if(textarea.value.indexOf("%0A") > -1){ Unix encodes returns as \n hex
textarea.value=textarea.value.replace("%0A",replaceWith)
}
else if(textarea.value.indexOf("%0D") > -1){ Macintosh encodes returns as \r hex
textarea.value=textarea.value.replace("%0D",replaceWith)
}
}
textarea.value=unescape(textarea.value) unescape all other encoded characters
}
<input type="button" onclick="escapeVal(this.form.area,'<br>')" value="Replace Carriage Returns with Break Tag">
Now the HTML-ized string is ready to be printed to a new window. If the script actually printed the string to a new window, the inclusion of the break tags could be done behind the scenes, rather than re-setting the textarea's value to include the break tags.
Removing Carriage Returns
Removing the carriage returns can be accomplished using the same function, except instead of replacing the encoded returns with a break tag, replace them with an empty string. The only change made is the value of the argument "replaceWith" when passed from the textarea. It is passed as an empty string rather than a break tag.
Replacing Carriage Returns with HTML Break Tags in Real Time
This script accomplishes the same task as the first, but does it in real time. This effect requires use of the event object and its key codes and character codes. Additional scripting is required for NN4 because of a bad habit it has which places the cursor at the beginning of a string instead of at the end when a value is entered by the script. The onKeyPress event handler is used to invoke the function in order for IE to obtain the alphanumeric character code for a carriage return.
// start with initializing nn4
var nn4 = (navigator.appName.indexOf("Netscape") > -1 && navigator.appVersion.indexOf("4") > -1) ? true : false
function addP(e,ta){ // e event object passed for NN4, ta is the textarea
var characterCode
if(e && e.which){ //get event object reference and code property for each browser
e = e
characterCode = e.which NN4
}
else{
e = event
characterCode = e.keyCode IE
}
if(characterCode == 13){ if enter key is pressed
if(nn4){
ta.value += "<br>%0D%0A" //encoding for \r\n must be manually entered
ta.value = unescape(ta.value) //must be unescaped in order for returns to be rendered inside textarea in real time
ta.select();ta.focus() //the select + focus combo forces NN4 to place cursor at end of string
return false
}
else{ IE
ta.value += "<br>" //simply add break tag when carriage return is pressed
return true
}
}
else if(characterCode == 8 && !document.getElementById){ //if backspace pressed (NN4) and browser is not NN6//IE ignores clause because this function is called onKeyPress & non alphanmerc backspace requires keydown or keyup
ta.value = ta.value.substring(0,ta.value.length-1) // unselect string & chop off last entered character
ta.select();ta.focus() //reselect & focus to force correct cursor insertion point
return false
}
else{ //if any other character is pressed
if(nn4){
ta.value += String.fromCharCode(characterCode)
//NN4 renders key/character codes so they must be converted back to plain language values for display using fromCharCode method
ta.select();ta.focus();
return false
}
else{
return true
}
}
}
<textarea rows="7" cols="50" onkeyPress="return addP(event,this)"></textarea>
Adding an argument to the function to be used as the string that replaces the encoded return could be done the same way it is in the first example to accomplish the task of removing the carriage returns in real time. However, I don't know that a remove-carriage-return script would have added value if accomplished in real time. But ya just never know!