javascript - What's a good way to build a character separated string from a collection? -
every once in while, need build character separated string while looping through collection. believe or not, there first or last separator character gets in way! :) usually, end chopping off character, line of code. leave that, out of curiosity, have cool "smooooth" way of doing this? (in c# and/or javascript)
example:
{"joe", "jane", "jim"}
after building comma separated string, get:
"joe, jane, jim, "
or ", joe, jane, jim"
looking cool way build
"joe, jane, jim"
without string "chopping" after.
in javascript it's easy:
var input = ["joe", "jane", "jim"]; var str = input.join(','); // output: joe,jane,jim
most languages have form of "join" either built-in or in library:
- javascript — it's a native function on array prototype
- php — implode
- java — apache commons lang
- c# — string.join
by way, if writing such function, should use check not prepend "glue" on first pass, rather chopping string afterward:
var items = ["joe","jane","john"]; var glue = ","; var s = ""; (var i=0; < items.length; i++) { if (i != 0) s += glue; s += items[i]; }
Comments
Post a Comment