Get updates

Scott Chomp for JavaScript

In most programming languages, there exist certain simple and useful functions that people come to rely upon. From my days with Perl, chomp was one of those functions for me.

Given a string, chomp bit off all newline characters at the end of the string (and returned the number of newline characters it removed).

Typically newline characters came from standard input, or data read from a file. JavaScript doesn’t usually deal with the latter, but input into a textarea may contain newline characters. Especially if it is actually, say, data copied from a spreadsheet and pasted into a form field for quick filtering and processing. At my day job I frequently handle data in spreadsheets, and quite often it’s easier to filter that data using regular expressions than Excel’s functionality.

So far I have not found a reason for wanting to know how many newlines chomp strips from a string, but a simple JavaScript implementation of chomp sans that feature looks like this:

function chomp(raw_text)
{
  return raw_text.replace(/(\n|\r)+$/, '');
}

Another step here would be to extend the String object, add this as a method to the prototype, which I may tackle next time.

One Response to “Chomp for JavaScript”

  1. Scott VR Says:

    How about this?

    String.prototype.chomp = function () {
    return this.replace(/(\n|\r)+$/, '');
    }

    Your post prompted me to include that in my standard library. Thanks.

Leave a Reply


Fatal error: Call to undefined function show_subscription_checkbox() in /home/dmetro/3dmdesign.com/wp-content/themes/hex_columns/comments.php on line 90