0

I initiated a numerical array inside a JavaScript and to converted it into a string using join but when I try to get a substr, it doesn't to work. There seems to be a technical error. Please help!

var array = [85, 13, 7, 42, 78, 9];
$("#div1").html("<b>This is the original array:</b><br><br>" + array.join("<br>"));

$("#div2").html("<br><b>This is the converted string:</b><br><br>" + array.join(""));

$("#div3").html("<br><b>The substring (from 0 to 3) is:</b><br><br>" + array.substr(0,3));

NOTE: div1, div2, div3 are 3 seperate divs with ids respectively. That's where I want to display the results.

4
  • 1
    You're calling substr on the array and not on the result of array.join. The join function does not modify the array, it returns a string Commented Apr 19, 2015 at 18:27
  • you mean if i save the result of array.join in a var result and then perform a var.substr() , it should work? Commented Apr 19, 2015 at 18:30
  • Yes, it should, unless there's something else wrong with your code. Commented Apr 19, 2015 at 18:31
  • ok i got it. this worked array.join("").substr(0,3) Commented Apr 19, 2015 at 18:32

1 Answer 1

1

You're calling substr on the array and not on the result of array.join. The join function does not modify the array, it returns a string

You have to assign the result to a variable and call substr on the resulting string value.

var joined = array.join("");
joined.substr(0,3); // this will work
Sign up to request clarification or add additional context in comments.

Comments

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.