im trying to make a small name summary function depending on the size of the elements container, here's what I have;
function shorten_tex开发者_开发知识库t(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:
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
精彩评论