I’m John C Bland II

Husband, Father, Tech Author, Deacon.
Founder ofย Katapult Media, and full-stack polyglot developer.
Political Free Agents Podcast Host.

I create. I launch.

YouTube Channel

I post regular fun on YouTube like me playing the bass and anything else I find fun.ย 

Get Something Built

All project work goes through Katapult Media. Business is open. Let’s chat.

I didn’t spend time looking through any of the JS utilities to do this so if there is one publicly available I’d suggest using it since I just coded this and haven’t run it through be 2 screen refreshes. ๐Ÿ™‚

bq. function trimByWord(sentence) {
var result = sentence;
var resultArray = result.split(” “);
if(resultArray.length > 10){
resultArray = resultArray.slice(0, 10);
result = resultArray.join(” “) + “…”;
}
return result;
}

I guess we can step through the code.

#) Set _result_ to the _sentence_ value passed in so if there aren’t more than 10 words it will just return the same string.
#) Split _result_ by spaces so a sentence like “I love to blog but sometimes get to busy. I’ll try harder.” will result in an array of 12 strings.
#) If _resultArray_ has more than 10 (put whatever number you want here) words, go to the next step. If not, skip to the last step.
#) Slice the array to only grab the first 10 (again, whatever number you want here) elements (the words) in the array.
#) _join()_ the array with a space so the _resultArray_ elements are now a string and add the ellipsis to the end.
#) Return the _result_.

That’s it. There are a few upgrades I’m going to make in a few minutes. Basically make sure the last character isn’t a period (if so, ignore the “…”) and maybe a couple others.

Hope this helps.