Replacing Line Breaks With <br /> Tags Using JavaScript

February 22nd, 2012 - Posted by Steve Marks to Javascript / jQuery, Web Development.

A 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.

This entry was posted on Wednesday, February 22nd, 2012 at 9:39 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first