Reputation: 809
function truncate(str, num) {
if(str.length < num) {
return str;
}
else {
str = str.slice(0, num);
return str;
}
}
truncate('A-tisket a-tasket A green and yellow basket', 11);
//truncate('A-tisket a-tasket A green and yellow basket', 'A-tisket a-tasket
A green and yellow basket'.length)
//truncate('A-tisket a-tasket A green and yellow basket',
'A-tisket a-tasket A green and yellow basket'.length + 2)
I need to have the code return 'A-tisket...' if the length of the string is longer than my num argument. When I run this code, it slices to 'A-tisket a-', how can I remove " a-" and add periods to the end when the length of string is longer than my num argument? I tried using .replace() method after .split() but cannot figure a way to replace it.
Upvotes: 2
Views: 2294
Reputation: 48425
Just trim more characters off the end (to make room for the periods) and then add the periods to the return value string.
I would also recommend you use <=
in your condition, otherwise you will end up adding dots when they are not needed.
Finally, for full resilience, you will want to ensure that you don't wrap around by 'slicing' with a negative length...
function truncate(str, num) {
if (str.length <= num) {
return str;
} else {
var append = "...";
var remove = num - append.length;
if (remove < 0) {
remove = 0;
append = append.slice(0, num);
}
str = str.slice(0, remove);
return str + append;
}
}
Upvotes: 1
Reputation: 1824
Ok! Good news is, you essentially have it already.
If you want to add ...
to the end, you've just about got it - just change return str
to return str + "...";
To ensure that we don't add ...
when num
is equal to the string's length, we can simply change <
to <=
.
So that gives you:
function truncate(str, num) {
if(str.length <= num) {
return str;
} else {
str = str.slice(0, num);
return str + "...";
}
}
Output:
truncate('A-tisket a-tasket A green and yellow basket', 11);
>>> "A-tisket a-..."
truncate('A-tisket a-tasket A green and yellow basket',
'A-tisket a-tasket A green and yellow basket'.length);
>>> "A-tisket a-tasket A green and yellow basket"
truncate('A-tisket a-tasket A green and yellow basket',
'A-tisket a-tasket A green and yellow basket'.length + 2);
>>> "A-tisket a-tasket A green and yellow basket"
Upvotes: 2
Reputation: 13570
You can use the + operator to concatenate the periods to the end of your string.
function truncate(str, num) {
if(str.length < num) {
return str;
}
else {
str = str.slice(0, num);
return str + "...";
}
}
Upvotes: 0