Steve
Steve

Reputation: 5166

Split comma-separated list and prepend character to each value

I would like to turn "one,two,three,four,five" into "$one $two $three $four $five".

Here is what I have so far to separate/explode the comma-separated list.

var str = 'one,two,three,four,five';
var str_array = str.split(',');

for(var i = 0; i < str_array.length; i++)
{
   // Trim the excess whitespace.
   str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   // Add additional code here, such as:
   alert(str_array[i]);
}

How can I prepend a character to each value and out them as space-separated list? It would be great to turn the code into a function that can be applied to a string.

Upvotes: 0

Views: 762

Answers (3)

Martin Jespersen
Martin Jespersen

Reputation: 26183

It is as simple as:

'$' + ('one,two,three,four,five'.split(',').join(' $'))

Here is a function that will do it, and output an empty string if there is no matches:

function (s) { 
  var a = s.split(',').join(' $'); 
  return a ? '$' + a : '';
}

Upvotes: 4

Praveen
Praveen

Reputation: 56509

Also we can use replace()

var str = 'one,two,three,four,five';
var str_array = str.split(',');

for (var i = 0; i < str_array.length; i++) {
    str = str.replace(',', '$');    
}
alert('$' + str);

Upvotes: 0

J David Smith
J David Smith

Reputation: 4810

Use the + operator and join:

for(var i = 0; i < str_array.length; i++) {
    str_array[i] = 'a' + str_array[i];
}
var out_str = str_array.join(' ');

Replace 'a' with whatever character you wish to prepend.

Upvotes: 1

Related Questions