I suggest not trying to use a regular expression at all, but just some
straight-up array manipulation. It makes it easier to handle all the special
cases involved here.

Paste this code into the multiline Firebug console (orange up arrow in the
bottom right of the Firebug panel) and hit Ctrl+Enter to run it:

function commasAnd( array ) {
    if( array.length < 2 ) return array.join('');
    var first = array.slice( 0, -1 ), last = array.slice( -1 );
    var result = first.join(', ');
    if( last ) {
        if( first.length > 1 ) result += ',';
        result += ' and ' + last;
    }
    return result;
}

function test( array ) {
    console.log( '"' + commasAnd(array) + '"' );
}

test([]);
test([ 'a' ]);
test([ 'a', 'b' ]);
test([ 'a', 'b', 'c' ]);
test([ 'a', 'b', 'c', 'd' ]);

It should display:

""
"a"
"a and b"
"a, b, and c"
"a, b, c, and d"

I took the liberty of following the English usage that is traditionally
considered correct: "a, b, and c", not "a, b and c". If you prefer "a, b and
c", you can remove the line with the first.length > 1 test.

-Mike

> From: ricardobeat
> 
> I'm not very good with regexes but this should do, just make 
> sure you always have a space after the comma:
> 
> levels.join(',').replace(/(\,)(.[^,]*)$/,' and$2')
> 
> I'm sure someone else can come up with a much more elegant expression!
> 
> - ricardo

> On Nov 22, 3:10 pm, shapper <[EMAIL PROTECTED]> wrote:
> > Hello,
> >
> > I have the following code:
> >
> > $levels = $('input[name="Levels"]:checked + label'); levels = 
> > $levels.map(function() { return $(this).text(); }).get(); 
> > $theme.append(levels.join(", ")).append('<br />');
> >
> > How can I replace the last comma in levels by " and "?
> >
> > I tried:
> > levels.join(", ").replace(/, $/,'and ')
> >
> > This is not working.
> >
> > Could someone, please, help me?
> >
> > Thanks,
> > Miguel
> 

Reply via email to