SwitchUp SwitchUp Ranked Best Coding Bootcamps 2025

Truncate a string (Basic Algorithm Scripting)

Altcademy Team wrote on 7 February 2018

Hi everyone,
This is my solution for Truncate a string

My solution works but I don't like my code(too many if else statement).Is there a better way to solve this problem?
Thank you.
function truncateString(str, num) { // Clear out that junk in your trunk var a=str.length; if(a > num && num>3){ var b=3; var c=a+b-num; return str.slice(0,-c)+"..."; }else if(a===num){ return str; }else if(a<num){ return str; }else if(num<=3){ return str.slice(0,num)+"..."; } else{ return false; } } truncateString("A-tisket a-tasket A green and yellow basket", 11);

Hey Nadim, have you checked out the following solution?

https://ask.hackpacific.com/questions/truncate-a-string

function truncateString(str, num) { // Clear out that junk in your trunk if (str.length > num) { if (num <= 3) { return str.slice(0, num) + "..."; } return str.slice(0, num - 3) + "..."; } return str; } truncateString("A-tisket a-tasket A green and yellow basket", 11);

Trusted by

Students and instructors from world-class organizations

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #97

Enroll for January 6th, 2025