Skip to content

Instantly share code, notes, and snippets.

@lossendae
Forked from cvergne/stringUtils.js
Created May 30, 2018 21:15
Show Gist options
  • Save lossendae/83e722d8214d862aab94c5ed83800a6d to your computer and use it in GitHub Desktop.
Save lossendae/83e722d8214d862aab94c5ed83800a6d to your computer and use it in GitHub Desktop.
Little javascript method to get initials from a name
String.prototype.getInitials = function(glue){
if (typeof glue == "undefined") {
var glue = true;
}
var initials = this.replace(/[^a-zA-Z- ]/g, "").match(/\b\w/g);
if (glue) {
return initials.join('');
}
return initials;
};
String.prototype.capitalize = function(){
return this.toLowerCase().replace( /\b\w/g, function (m) {
return m.toUpperCase();
});
};

To use it, very simple, include this javascript anywhere you want (but before calling it), then:

"Tommy Lee Jones".getInitials();

It will return TLJ.

If you prefer to get an array of initials, call "Tommy Lee Jones".getInitials(false);, then it will return an array.

Currently, due to JS regex limitations, it doesn't support well special chars. So it removes special chars to avoid wrong initials.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment