Skip to content

Instantly share code, notes, and snippets.

@cvergne
Last active September 25, 2024 14:15
Show Gist options
  • Save cvergne/7244472d3e1f1ca7ee56 to your computer and use it in GitHub Desktop.
Save cvergne/7244472d3e1f1ca7ee56 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