Replace Line Feeds With Commas Using Javascript

The following JavaScript function can be used to replace line feeds and carriage returns with commas. I find this particularly useful when formatting a data column from Excel into an SQL constraint.

Sample Input:

1
2
3
4
5

Sample Result:

1,2,3,4,5

The JavaScript function uses a simple regular expression to remove line feeds and carriage returns. The comma as the second argument to the ref.value.replace function may be replaced with any other character to meet your specific requirement.

function remove_crlf(ref) {
  ref.value = ref.value.replace(new RegExp("\r\n", "gi"), ",");
}

Using a simple HTML page with a Text Area, we can paste the data list into the form. When the cursor is moved away from the Text Area, the function is automatically called and the list is formatted with commas replacing the line feeds and carriage returns on each line.

Putting all of the code together, we get the following which can be saved to an html file.

<html>
  <head>
    <script language='javascript'>
      function remove_crlf(ref) {
        ref.value = ref.value.replace(new RegExp("\r\n", "gi"), ",");
      }
    </script>
  </head>
  <body>
    <form name='frmremover'>
      <textarea
        name="txtdata"
        rows="20"
        cols="80"
        onblur="javascript:remove_crlf(this)">
      </textarea>
    </form>
  </body>
</html>

Leave a Comment