Created
June 7, 2018 21:07
-
-
Save Kaeyz/d20c28d21efaf3b46bd25b7703ce6fec to your computer and use it in GitHub Desktop.
freecodecamp challenge: Truncate String function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function truncateString(str, num) { | |
if (str.length <= num) { | |
console.log(str); | |
return str; | |
} else { | |
var newStr = []; | |
var nstr = str.split(""); | |
for (let index = 0; index < num; index++) { | |
newStr.push(nstr[index]) | |
} | |
str = newStr.join('') + '...'; | |
console.log(str); | |
return str; | |
} | |
} | |
truncateString("A-tisket a-tasket A green and yellow basket", 8) ; | |
truncateString("Peter Piper picked a peck of pickled peppers", 11) ; | |
truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) ; | |
truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) ; | |
truncateString("A-", 1); | |
truncateString("Absolutely Longer", 2) ; |
/*
* credits Kaeyz (Kolade)
// permission to reuse
! link https://github.com/Kaeyz
? FreeCodeCamp Ibadan
*/
// TODO write the code below
function truncateString(str, num) {
let store = []
let strArray = str.split('');
if (str.length <= num) {
return str
} else {
for (let index = 0; index < num; index++) {
store.push(strArray[index])
}
// str = output.join('') + '...';
return store.join('').concat('...')
}
}
truncateString("A-tisket a-tasket A green and yellow basket", 8)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can just remove the log to console part, I think. Other than that, fine code. Also make it a bit more declarative. Thanks
var newStr = [];
newStr should be something like array (it is not a string)