1

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.

5
  • 2
    If you want a string and you have a string, why are you splitting it back into an array? That's what split does. Commented Jun 13, 2013 at 13:51
  • 1
    While you certainly can convert an array to a string (really depends on its values), the question is: Why? Commented Jun 13, 2013 at 13:53
  • I need to replace the , with new line, was assuming making a string is easiest way. from there I can just use replace method, I think? Commented Jun 13, 2013 at 13:54
  • It seems like you just want optionTexts.join('\n') or optionTexts.join('<br>'). Commented Jun 13, 2013 at 13:56
  • @FelixKling oh, yeah that definitely is a lot cleaner. thanks. Commented Jun 13, 2013 at 13:57

1 Answer 1

1

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(",");
1
  • optionTextString should be optionText. Commented Jun 13, 2013 at 13:59

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.