Truncate a string need help plz

Oh yes ! thanks ! Now you tell me that I know my ‘solution’ is more complicated and more longer to write.

Because as you said I can just put => return str.slice(0, num) + “…”;

But I just wanna say I am a beginner and sometimes code seems a little bit complicated in my head. And I sometimes It takes times to undertand instructions because my native language is french.

Thank you very much !

1 Like

You’re right thank you so much :smile:

We are all guilty of sometimes writing code that is over-engineered or more complicated than it needs to be.

One thing I would suggest is to try and keep data types the same when possible. That is unless changing it gives you some advantage. So if you have a string and need to perform a string operation, see if you can just use a string first.

Anyway, good job passing the challenge.

1 Like

Thanks for your suggestions and advice, it is very helpful

The simplest truncate function I can think of would be like this:

function truncateString(string,  length) {
  if (string.length > length) {
    return string.slice(0,  length)  +  "...";
  }
  
  return string;
}

The thing here is that we only want to check how large the input is against a specific max length allowance and if it is too big, add a “…” after that limit. We achieve this with a quick if statement and a string slice. Otherwise we can assume the input string was fine and just return it as is.

1 Like

Thanks ! That’s very simple to write and very elegant in my opinion. I think this is the kind of solution Iasjorg suggested me, he gives me a hint like that. Thanks for responding. That’s very helpful !