Skip to content

Instantly share code, notes, and snippets.

@Jberivera
Last active December 22, 2017 15:17
Show Gist options
  • Select an option

  • Save Jberivera/86edd1d174baa4590e7d423e537455ad to your computer and use it in GitHub Desktop.

Select an option

Save Jberivera/86edd1d174baa4590e7d423e537455ad to your computer and use it in GitHub Desktop.
/**
* getLastWord - Splits the given string in
* its last word and pass the result into the callback
*
* @param {String} str
* @param {Function} callback - Takes as arguments the first part of the text (without the last word) and the last word.
*/
export function getLastWord(str, callback) {
if (typeof str !== 'string') str = '';
const LAST_WORD_REGEXP = /(.+)\s((?:.+)?\S$)/;
const match = str.trim().match(LAST_WORD_REGEXP);
if (!match) return callback('', str);
const group1 = match[1] || '';
const group2 = match[2] || '';
return callback(group1, group2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment