Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am having a JavaScript array and I want to convert this array into string with a separator, in a way PHP implode does.

e.g.

var daysArr = [];
daysArr.push('monday');
daysArr.push('tuesday');

I want to get "monday*tuesday"

How can we achieve this?

Thx.

share|improve this question

5 Answers 5

up vote 3 down vote accepted

Try using this

daysArr.join('*');

NameOfArray.join('separator');

share|improve this answer
    
Working, Thanks. +1 for this –  Jatin Dhoot Jul 6 '11 at 12:27
    
I tried doing that, but there is a constraint in place which says you can accept answer after 5 minutes –  Jatin Dhoot Jul 6 '11 at 12:34
    
Hmm, how strange. Probably a good thing in case better answers appear. –  JLevett Jul 6 '11 at 12:42

Use JavaScript function join

daysArr.join('*');
share|improve this answer
var arr = new Array();
arr[0] = "1";
arr[1] = "2";

alert(arr.join("*"));

Demo example.

share|improve this answer

This function should do it

<script>
var daysArr = [];
daysArr.push('monday');
daysArr.push('tuesday');

function implode(arr, sep) {
    //Output string
    output = '';
    //Counter
    j = 1;
    for (i in arr) {
        //Append
        output += arr[i];
        //Add seperater if not the last item
        if (j != arr.length) {
            output += sep;
        }
        j++;
    }
    //Return output
    return output;
}

alert(implode(daysArr, ','));
</script>
share|improve this answer
    
Oops, forgot about the join function! –  fin1te Jul 6 '11 at 12:27
    
Yup, we need not write this big heap of code, if it offered as default. Good try though –  Jatin Dhoot Jul 6 '11 at 12:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.