treehouse : what would you like to learn today?
Web Design Web Development iOS Development

JavaScript Array

  • Hi guys, I would like to know how to basically retrieve a certain number of characters from the string value inside of an array. So for example.

    var news = new Array();
    news[0] = \"Today a big thing happened that was really big, seriously big, I mean huge!\";
    news[1] = \"Today I saw a man. He was a man, not a women, an man, as in he was male, not female, defiantly male.\";
    news[2] = \"Today police discovered what appeared to be an oversized crunchy bar, just lying in the street - unopened.\";

    for(var i; i < 2; i++)
    {
    document.write(news[i]);
    }

    Where I have the "document.write" is where I would like there to be a amount of characters output limit, so for news[0] it could just be - "Today a big thing happened".

    How would I go about doing this, and is it even possible with JavaScript? Or am I better off going with XML?

    Thanks

    -Tom
  • That functionality is not build-in, but I'm not sure it's build into XML either. Maybe I'm a little confused but a function like this would work:

    function max(theString, maxCharacters){
    if(theString.length <= maxCharacters){
    return theString;
    } else {
    return theString.substring(0, maxCharacters);
    }
    }

    So instead of just doing document.write() you'd do document.write(max(news[i], 10)). Is that what you were asking for?
  • Im not 100% sure what your asking for but from what it sounds like your interested in extracting a substring.


    <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
    <head>
    <title>Test</title>
    <script type=\"text/javascript\">
    var news = new Array();
    news[0] = \"Today a big thing happened that was really big, seriously big, I mean huge!\";
    news[1] = \"Today I saw a man. He was a man, not a women, an man, as in he was male, not female, defiantly male.\";
    news[2] = \"Today police discovered what appeared to be an oversized crunchy bar, just lying in the street - unopened.\";

    for (var i = 0; i < 3; i++){
    document.write(news[i].substring(0,10) + \"<br />\");
    }
    </script>
    </head>
    <body>
    </body>
    </html>


    the above code would write all characters in each item from the 0 character (first character) up to (but not including) the 10th character of the strings. (PS: in a for loop that you will be incrimenting always include a value for the variable or it will throw an error and increase the number by 1 to go through an array. so if the array is 3 entries (0,1, and 2) write either i < 3 or i <= 2.
    Is this what you were lookin for?