JavaScript method that can add some character at the begining and end of another string

StackOverflow https://stackoverflow.com/questions/22912562

  •  29-06-2023
  •  | 
  •  

Pregunta

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.

¿Fue útil?

Solución

You could just do:

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = '{' + fruits.join('} {') + '}';

Otros consejos

JSFiddle

var energy = '{';
energy += fruits.join('} {');
energy += '}';
alert("Energy : " + energy);

You could get alert as

Energy : {Banana} {Orange} {Apple} {Mango}

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 } {.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top