In this brief explanation, we will quickly look at two ways how you can get the initials from a name in Javascript.
First will be regex way and if you do not know much about regex, it will probably be just a bunch of jibberish. So if you just want something to copy and have it working, this works just fine!
Secondly, is something that is actually readable.
1. Regex
regex or regular expression is a sequence of characters that specifies a search pattern in the text. In our example, the text will be the name.
So firstly, we will get the name.
const name = "Johan William Doe"
So let’s start with creating a function!
function getInitials(name) {
}
Then we will return the name .match with regex that will get the first letter of each string in a name and join it into a string
function getInitials(name) {
return name.match(/(\b\S)?/g).join("");
}
Now, if you tried to run it you might see that function will return this:
const initials = getInitials("Johan William Doe")
console.log(initials) // "JWD"
And what we want is just the first and very last initial in a name.
So what we need to do is slap another regex .match regex on it!
function getInitials(name) {
return name
.match(/(\b\S)?/g)
.join("")
.match(/(^\S|\S$)?/g)
.join("");
}
And there you go! This is how you get initials from a name in Javascript with regex.
You might be baffled by what does this even mean. No worries, it’s a regex, no one knows! But if you are interested in learning more about it or mastering it even, here you go!
2. More readable version
Once again let’s create a function for it.
function getInitials(name) {
}
next, we will split the name
function getInitials(name) {
const nameArray = name.split(" ")
}
In the next step, we will get the first and last name by selecting the first and last string and getting the first character.
function getInitials(name) {
const nameArray = name.split(" ")
const firstNameIn = nameArray[0].charAt(0).toUpperCase()
const lastNameIn = nameArray[nameArray.length - 1].charAt(0).toUpperCase()
}
Lastly, we will return first name + last name and we will be done, easy enough!
function getInitials(name) {
const nameArray = name.split(" ")
const firstNameIn = nameArray[0].charAt(0).toUpperCase()
const lastNameIn = nameArray[nameArray.length - 1].charAt(0).toUpperCase()
return firstName + lastName
}
And now you are getting initials from a string in a readable way. However, when performance is important, for example, if you have a long list of names then you should definitely use regex.