You have strings with a separator character (a space or something else) like the following:
"1 2 3"
"1 2"
"1"
What is the best/elegant way in Javascript to format them in the following way?
"1, 2 and 3"
"1 and 2"
"1"
Must works for any number of elements >= 1
You can use this:
Got this somewhere on StackOverflow a few years ago. This is a very basic implemenation -- it wouldn't be hard to add a delimiter parameter to the method.
A basic solution :
This one sticks to your own approach (trailing separator) :
Usage example :
This one works if you have an array too. It uses the Query $.inArray that can be omitted if you do not use jQuery and input only in array form or string form.
This one is pretty twisted :
Fails to handle consecutive and trailing separators though :