Grow your CSS skills. Land your dream job.

JavaScript Array

  • # May 6, 2009 at 2:29 pm

    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

# May 6, 2009 at 3:02 pm

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?

# May 9, 2009 at 4:51 pm

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

Code:





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)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".