Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript JavaScript Array

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #24808

    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.

    Code:
    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

    #57243
    akeenlabs
    Participant

    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:

    Code:
    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, 10)). Is that what you were asking for?

    #57376
    Stack
    Member

    Im not 100% sure what your asking for but from what it sounds like your interested in extracting a substring.

    Code:


    Test




    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?

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.