count linebreaks

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jeff Thies

    count linebreaks

    I need a quick way to count linebreaks. This is slug slow:

    function findLinebreaks( str) {
    var re='/\r\n|\n|\r\|\f/g';
    var i=0;
    while(re.match( str)){
    i++;}
    return i;
    }

    Cheers,
    Jeff


  • Ivo

    #2
    Re: count linebreaks

    "Jeff Thies" <nospam@nospam. net> wrote in message
    news:2%Hec.5312 $l75.246@newsre ad2.news.atl.ea rthlink.net...[color=blue]
    > I need a quick way to count linebreaks. This is slug slow:
    >
    > function findLinebreaks( str) {
    > var re='/\r\n|\n|\r\|\f/g';
    > var i=0;
    > while(re.match( str)){
    > i++;}
    > return i;
    > }
    >
    > Cheers,
    > Jeff
    >[/color]

    What is wrong with
    return str.split(/\r\n|\n|\r\|\f/)
    possibly with an extra check for the last character on the last line?
    HTH
    Ivo


    Comment

    • Martin Honnen

      #3
      Re: count linebreaks



      Jeff Thies wrote:
      [color=blue]
      > I need a quick way to count linebreaks. This is slug slow:
      >
      > function findLinebreaks( str) {
      > var re='/\r\n|\n|\r\|\f/g';
      > var i=0;
      > while(re.match( str)){
      > i++;}
      > return i;
      > }[/color]

      What happends when you use a regular expression literal and only the
      test method:

      function countLineBreaks 1 (string) {
      var pattern = /\r\n|\r|\n/g;
      var count = 0;
      while (pattern.test(s tring)) {
      count++;
      }
      return count;
      }

      --

      Martin Honnen


      Comment

      • Jeff Thies

        #4
        Re: count linebreaks

        The winner is:

        return str.split(/\n|\f/).length;

        much much much faster.

        The \r\n part of my test caused problems with IE not counting blank lines.
        The \f is for Macs.

        Cheers,
        Jeff[color=blue]
        >
        >
        > Jeff Thies wrote:
        >[color=green]
        > > I need a quick way to count linebreaks. This is slug slow:
        > >
        > > function findLinebreaks( str) {
        > > var re='/\r\n|\n|\r\|\f/g';
        > > var i=0;
        > > while(re.match( str)){
        > > i++;}
        > > return i;
        > > }[/color]
        >
        > What happends when you use a regular expression literal and only the
        > test method:
        >
        > function countLineBreaks 1 (string) {
        > var pattern = /\r\n|\r|\n/g;
        > var count = 0;
        > while (pattern.test(s tring)) {
        > count++;
        > }
        > return count;
        > }
        >
        > --
        >
        > Martin Honnen
        > http://JavaScript.FAQTs.com/
        >[/color]


        Comment

        Working...