views:

76

answers:

1

Hello, im trying to make a small name summary function depending on the size of the elements container, here's what I have;

function shorten_text(str, size){
    size = size.match( /[0-9]*/ );
    var endValue = Math.floor( Number(size) / 10 );
    var number;
    var newStr;
    for ( number = 0; number <= endValue; number++ ) {
        if( str[number].length != 0 ) {
            newStr += str[number];
        }
    }   
    return newStr + '...';

}
shorten_text('Phil Jackson', '94px');
// output should be 'Phil Jack...'

What I seem to get is undefinedundef... can anyone see where I am going wrong?

EDIT:

revised code based on comments below for anyone who is googling for such function:

function shorten_text(str, size){
    size = parseInt(size);
    var endValue = Math.floor(size / 10);
    if( str.length > endValue ) {
        return str.substring(0, endValue) + '...';
    }else{
        return str;
    }
}

SCREEN SHOT:

screenshot

+3  A: 

You need to initialize your newStr variable with an empty string, otherwise that variable will contain the undefined value, which will be converted to string when you concatenate, e.g.:

var test; // at this moment the variable contains the undefined value
test += 'foo';
// now test contains "undefinedfoo"

In your function:

function shorten_text(str, size){
    size = size.match( /[0-9]*/ );
    var endValue = Math.floor( Number(size) / 10 );
    var number;
    var newStr = '';
    for ( number = 0; number <= endValue; number++ ) {
        if( str[number].length != 0 ) {
            newStr += str[number];
        }
    }   
    return newStr + '...';
}

shorten_text('Phil Jackson', '94px'); //  outputs "Phil Jacks..."

A few comments:

  • You don't need to call Number(size), since the division operator makes type coercion. implicitly
  • You could use the substring method to get a portion of your original string.
  • Accessing characters of a string with the square bracket property accessor may not be supported by some implementations, you can use the standard charAt method (str.charAt(i))

Another approach to do the same:

function shorten_text(str, size){
    var endValue = Math.floor(parseInt(size) / 10);
    return str.substring(0, endValue) + '...';
}

shorten_text('Phil Jackson', '94px'); //  outputs "Phil Jack..." as expected
CMS
Thank you very much, very informative. I m here to learn! ( and works like a charm )
Phil Jackson
tuche, does save time and space!
Phil Jackson
The shorter shorten_text outputs a slightly different answer ('Jack' instead of 'Jacks') -- needs a "+1" if you want the same. I'm going to delete my own now-redundant answer.
Darius Bacon
@Darius: Yes I noted this, but the OP expects to get 'Phil Jack...' (look the comment on the question)
CMS