Updated Answer
It just dawned on me that you could actually trim this down a little further, by using the .join
method for arrays:
var namePieces = names[i].replace(/@.+$/, "").split(".");
for (i=0; i<namePieces.length; i++) {
namePieces[i] = namePieces[i].replace(/^[a-z]/, function(match) {
return match.toUpperCase();
});
}
var cleanName = namePieces.join(" ");
. . . or, if you are returning the cleanName
value, for that last line, you could just use:
return namePieces.join(" ");
That would actually just convert the first letter of each element in the namePieces
array to uppercase and then join
all of the updated elements together, with a space separating each element.
Original Answer
Here's an alternate approach . . . based on your code, you could do this:
var namePieces = names[i].replace(/@.+$/, "").split(".");
var cleanName = "";
for (i=0; i<namePieces.length; i++) {
cleanName += (i > 0) ? " " : "";
cleanName += namePieces[i].replace(/^[a-z]/, function(match) {
return match.toUpperCase();
});
}
Now, let me step through the code . . . :)
var namePieces = names[i].replace(/@.+$/, "").split(".");
This takes the current email address, strips off everything after the @
, and splits the remaining values, into an array, every time it hits a .
The result of your sample data Firstname.Lastname@email-domain.co.uk
, would be this array: ["Firstname", "Lastname"]
After that, it goes through each item in the array and adds a space to the existing cleanName
value, if it is not the first element in the namePieces
array:
cleanName += (i > 0) ? " " : "";
Then it takes the current name "piece" and, if it's first character is a lowercase letter, replaces it with the uppercase version of itself, and adds it to the current cleanName
value:
cleanName += namePieces[i].replace(/^[a-z]/, function(match) {
return match.toUpperCase();
});
Two things to note about this approach:
- It skips the replace if it not a lowercase letter for a little extra speed. If you need to account for non-alpha characters (other languages, symbols, numbers), this regex would have to be altered to either accept any character (i.e.,
/^./
) or change the set of acceptable characters in the regex. This approach will also pick up other variations of the names in the email address . . . for example:
Firstname.M.Lastname@email-domain.co.uk
would result inFirstname M Lastname
Firstname.Lastname.Jr@email-domain.co.uk
would result inFirstname Lastname Jr
So that might add a little extra flexibility.