-
Notifications
You must be signed in to change notification settings - Fork 341
Bonfire Truncate a string
Created by Rafase282
Github | FreeCodeCamp | CodePen | LinkedIn | Website | E-Mail
- Difficulty: 1/5
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a '...' ending.
Note that the three dots at the end add to the string length.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
function truncate(str, num) {
// Clear out that junk in your trunk
return str;
}
truncate('A-tisket a-tasket A green and yellow basket', 11);
We need to reduce the length of the string or truncate it if it is longer than the given maximum lengths specified and add ...
to the end. If it is not that long then we keep it as is.
Strings are immutable in JavaScript so we will need a new variable to store the truncated string.
You will need to use slice and specify where to start and where to stop.
Do not forget that when we truncate the word, we also must count the length added by ...
function truncate(str, num) {
var truncd = '';
if (str.length > num) {
truncd = str.slice(0,num-3) + '...';
return truncd;
}
return str;
}
- Create a variable
truncd
to store the truncated string. - Check to see if the string needs to be truncated.
- If so, then slice the string and make sure you include the three dots.
- Return the truncated word or the original string if it didn't need to be truncated.
Thanks for visiting, if you like this please feel free to star my repo, follow me or even contact me about contributing as it will be a lot of work and having help would be cool.
- HTML5 and CSS
- Responsive Design with Bootstrap
- Gear up for Success
- jQuery
- Basic JavaScript
- Object Oriented and Functional Programming
- Basic Algorithm Scripting
- Basic Front End Development Projects
- Intermediate Algorithm Scripting
- JSON APIs and Ajax
- Intermediate Front End Development Projects
- Claim Your Front End Development Certificate
- Upper Intermediate Algorithm Scripting
- Automated Testing and Debugging
- Advanced Algorithm Scripting
- AngularJS (Legacy Material)
- Git
- Node.js and Express.js
- MongoDB
- API Projects
- Dynamic Web Applications
- Claim Your Back End Development Certificate
- Greefield Nonprofit Project 1
- Greefield Nonprofit Project 2
- Legacy Nonprofit Project 1
- Legacy Nonprofit Project 2
- Claim your Full Stack Development Certification
- Whiteboard Coding Interview Training
- Critical Thinking Interview Training
- Mock Interview 1
- Mock Interview 2
- Mock Interview 3