Creating an excerpt whilst preserving words

Julien Etienne Demonstration of creating an excerpt from text

by Julien Etienne

HTML

<<h1>Creating an excerpt whilst preserving words</h1>

JavaScript

// Creating an excerpt whilst preserving words
// Julien Etienne 04/01/2021
const K = 14;


const exampleText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean suscipit libero rutrum risus rhoncus, id efficitur eros vestibulum. Curabitur ut erat in lectus rutrum gravida. Quisque tempus, magna quis dictum tempus, dolor erat congue justo, eget ultrices ante diam placerat lorem. Mauris tincidunt sagittis massa sit amet porttitor. Donec commodo lectus sit amet erat ultricies finibus. Nunc porttitor erat sed nisi porta, a pellentesque urna accumsan. Nunc sagittis tincidunt risus sit amet euismod. Phasellus eu laoreet nisl, fringilla blandit eros. Curabitur quis urna in dui eleifend facilisis at a erat."

  // Node.js 8.x does not support trimEnd 
 /**
 * String.prototype.trimEnd() polyfill
 * Adapted from polyfill.io
 */
  if (!String.prototype.trimEnd) {
    String.prototype.trimEnd = function () {
      return this.replace(new RegExp(/[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/.source + '$', 'g'), '');
    };
  }
  

const createExcerpt = (T, K) => {
	if(typeof T !== 'string') return '';

	// Trim the end 
	const text = T.trimEnd();
	
	if(text.length < 2){
  	return '';
  }

  // If the limit is greater than the text length do nothing
  if(K >= text.length){
  	return text;
  }; 
  
  const limitedText = text.substr(0,K);

  // Else check if the character at the limit is a space
  if(text[K] === ' '){
  	return limitedText.trimEnd();
  }
  
  // Find the earliest space from the chop
  const lastFullWordIndex = limitedText.lastIndexOf(' ');
     console.log('test', K)
    
  // Where K is shorter than the first word, preserve the word. 
  const firstSpaceIndex = text.indexOf(' ');
  if(K < firstSpaceIndex + 1){
  	return '';
  }
 

/*
  	If last space starts at the beginning or does not exist
    The end-trimmed text is used
  */ 
  if(lastFullWordIndex...