Replace Line Feeds With Commas Using Javascript

The following JavaScript function can be used to replace a line feed and carriage return with a comma. 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 Function:

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 it all together:

<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