How to insert <BR> in textarea

Hi, I have a texarea form field from which customers can enter their comments.

How can I automaticaly insert a <br> tag when “enter” is hit within the textarea? At the moment the text all runs on one line … thanks


An invisible carriage return character is inserted when you hit Enter. On Windows, it is "\r
", on Macs it’s “\r”, and on Unix systems it’s "
". The js string functions or regexes can detect those invisible characters. The basic approach is to search for either "\r
" or “\r” or "
" and convert them to all to the same carriage return character. Since the proposed standard is "\r
", you can use that:

var normalized_Enters = text.replace(/\r|
/g, "\r

That way no matter what operating system the user employs, all the carriage returns will be \r
. Then, you can replace the \r
with <br /> tags.

var text_with_br = normalized_Enters.replace(/\r
/g, “<br />”);

So, you should end up with a function that looks something like this:

function insert_br(text)
	var normalized_Enters = text.replace(/\\r|\
/g, "\\r\
	var text_with_br = normalized_Enters.replace(/\\r\
/g, "<br />");
	return text_with_br;


(Tested with IE6 and FF1.0 on windows) One of the masters of the universe addressed this thorny issue here:

On the other hand, if you want to insert break tags for carriage returns while the user is typing, then it’s a bit more involved, and it requires using the onkeypress event to detect the Enter key and/or content editable, as well as several cross browser issues. Check out this website for several solutions:

(although even after reading the article, I am still unable to get a regex to detect a carriage return)

as you type


<textarea rows="10" cols="50" id="myID" onfocus="javascript:vtbID='myID;" onblur="javascript:vtbID=null;">


<script language="JavaScript" type="text/javascript">
// modified from Verify Text Box Input Part 2 (21-04-2004)
// by Vic Phillips

var vtbID=null;

function vtbKeyPress(e){
 if (vtbID==null){ return }
 if (!document.all){ if (e.which!=8&&e.which!=13){  return;  }  }
  else { if (event.keyCode!=8&&event.keyCode!=13){ return;  }  }

if (!document.all){




onfocus=“javascript:vtbID=vtbid;” onblur=“javascript:vtbID=null;”>

You sure that’s correct? What’s ‘vtbid’? It doesn’t look to me like it exists anywhere, so I think it will produce an ‘undefined error’.

And, where is the script adding <br /> tags?

have edited my previous code

now adds </br> when enter/return key pressed in text area

tested with IE but should work with FF

Why two ‘if(!document.all)’ statements?

Why write such tortured code as this:

if (e.which!=8&&e.which!=13)

Are any short cut efficiencies really worth making your code unreadable–especially when you are posting it to a forum to help someone? Along with your indent style(is there even a closing brace for your function?), I find your code almost impossible to follow, and it’s only a few lines long. :frowning: