2

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.

5 Answers 5

3

Try using this

daysArr.join('*');

NameOfArray.join('separator');

Sign up to request clarification or add additional context in comments.

2 Comments

I tried doing that, but there is a constraint in place which says you can accept answer after 5 minutes
Hmm, how strange. Probably a good thing in case better answers appear.
1

array.join(separator)

Comments

1
var arr = new Array();
arr[0] = "1";
arr[1] = "2";

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

Demo example.

Comments

0

Use JavaScript function join

daysArr.join('*');

Comments

0

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>

2 Comments

Oops, forgot about the join function!
Yup, we need not write this big heap of code, if it offered as default. Good try though

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.