Replacing Line Breaks With <br /> Tags Using JavaScript
Posted in Javascript / jQuery, Web Development on February 22nd, 2012 by Steve Marks – Be the first to commentA scenario arose today where I needed to take the content within a textarea and then output it the screen as HTML. In doing this I knew I would have to take the line breaks in the textarea content (\n) and swap them out for <br /> HTML tags. Languages like PHP come with inbuilt functions to handle this kind of replacement. JavaScript however does not.
I started out by trying the following:
var output = document.form1.myTextarea.value.replace("\n", "<br />");
This kind of worked but only replaced the first line break. I then remembered from previous posts that the JavaScript replace() function will only swap out the first occurrence of a string.
A quick change was required to the code as follows:
var output = document.form1.myTextarea.value.replace(/\n/g, "<br />");
By turning the first parameter into a regular expression and enabling ‘global’ matching (\g), all line breaks were now being converted as expected.




Hi, I'm Steve Marks, the voice (or at least the typist) behind this blog. I'm 24 and currently live in the UK.