Skip to content

Instantly share code, notes, and snippets.

@jamesholcomb
Last active April 8, 2019 20:28
Show Gist options
  • Save jamesholcomb/c9a3c51424f8250a8a90663a3ca1d215 to your computer and use it in GitHub Desktop.
Save jamesholcomb/c9a3c51424f8250a8a90663a3ca1d215 to your computer and use it in GitHub Desktop.
Perform a best effort extraction of up to two initials from a space delimited name string
/**
* Perform a best effort extraction of up to two initials from a space delimited name string
* @param {string} text The text
* @return {string} The result
*/
function initials(text) {
if (!text) {
return ""
}
// extract letters, diacritics
const r = /[A-Za-zÀ-ÖØ-öø-ÿ]/i
const tokens = text.split(" ").slice(0, 2)
let result = ""
for (let i = 0; i <= tokens.length - 1; i++) {
const m = tokens[i].match(r)
if (m) result += m[0].toLocaleUpperCase() + " "
}
return result.trimRight()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment