Get the first two words and truncate this line | Truncate a String

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

function truncateString(str, num) {
return str;
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.85 YaBrowser/21.11.4.727 Yowser/2.5 Safari/537.36

Challenge: Truncate a String

Link to the challenge:

Greetings all!

I managed to solve this problem on my own, and I would like to change it a little bit.

Instead of characters in a string, I would like to take the first few words, and end it with a ellipsis.

I haven’t been able to solve this issue for myself for an hour, tell me which direction I need to go.

Thank you.

You can do the following

  1. Split the sentence in words using String.prototype.split() method
    Note: This will return an array

  2. Then use the Array.prototype.slice() method to trim the words

  3. Finally use Array.prototype.join() method to merge them back

Feel free to reply back in case you get stuck somewhere.

1 Like

Thank you!
Could you show me an example of the code?

First, we take the string and divide it into words using the split method, the argument white space is the separator here (you can use hyphen or period if you want to split based on them)
Note: This returns an array.

Second, we use the slice method to get n number of words. The first argument is the start of the array and the second is the end of the array.

Third, we join the sliced array back to a string.

I’ve provided the documentation link in my previous post, you could refer to that for more details on the prototype methods.

function truncateString(str, num) {
    return str.split(' ').slice(0, num).join(' ');
}
truncateString("A-tisket a-tasket A green and yellow basket", 3);

Output: A-tisket a-tasket A

1 Like

Thank you very much, you have helped me a lot!
And how can I eliminate the hyphen from here, and get the next word out?
By using regular expressions?

I think you could use regular expression, but the implementation depends on how you need the output

These must be the first two words in the text, excluding spaces and any other punctuation marks.

A sample input and output will describe the requirement more clearly.

Give that a try on your own if you have already completed the regex section. This will help you write regex more easily and concisely.

You can try writing your regex in the following sites (I’m not affiliated to any site, just sharing some resources that I find helpful).

1 Like