Snippet day: last comma becomes “and”

This little snippet will replace the last comma in a string by the word ” and “. Making it more readable for the end user.

In other words: the string “Other examples are rats, mice,other rodents” will be converted into “Other examples are rats, mice and other rodents”.


var a : Array = ["rats","mice","other rodents"];
var s : String = a.toString(); // returns rats,mice,other rodents
var r : RegExp = /,(?![^,]+,)/g; // the magical formula
s = s.replace( r ," and "); // replace the last , with and
trace( s ); // rats, mice and rodents

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>