Reputation: 19163
I have been using join() which "Join the elements of an array into a string".
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join();
results in Banana,Orange,Apple,Mango
Do we have a method which can result in something like this
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.New_Method('{','}');
should result in
{Banana} {Orange} {Apple} {Mango}
I can do this with the help of for loop but I want to know if there is any inbuilt method which can do this for me.
Upvotes: 0
Views: 75
Reputation: 7668
var energy = '{';
energy += fruits.join('} {');
energy += '}';
alert("Energy : " + energy);
You could get alert as
Energy : {Banana} {Orange} {Apple} {Mango}
Upvotes: 1
Reputation: 664444
There's also a functional way, resembling more what you want to express (without repetition of the wrapper chars):
var energy = _.map(fruits, function wrap(f) { return '{'+f+'}'; }).join(' ');
However, this is probably slower than joining by } {
.
Upvotes: 0
Reputation: 15213
You could just do:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = '{' + fruits.join('} {') + '}';
Upvotes: 5