Lukasz
Lukasz

Reputation: 97

Convert array(object?) to string in javascript

I am trying to convert this array into a string but it gives me the error:

Object [object Array] has no method 'split'

I am converting to a string, so it shouldn't have that problem, I'm not sure why I am getting this error.

My code is:

function preSubmit(){
    var optionTexts = [];
    $("section").each(function(){
        var h2 = $(this).find("h2").text();
        optionTexts.push(h2);
        $("ol li", this).each(function() { optionTexts.push($(this).text()); });
    });
    var optionTextString = optionTexts.toString();
    var splitText = optionTextString.split(",");
    console.log(splitText);
    return splitText;
}

The returned value of typeof splitText gives me [object Array], but I expect string.

Upvotes: 1

Views: 1009

Answers (1)

Oscar
Oscar

Reputation: 13960

And it's true, array doesn't have any split method. You're messing Join and Split methods, one belong to array, the other to string functions.

What you want is:

var splitText = optionTextString.join(",");

Upvotes: 1

Related Questions