I have been struggling with a regular expression to get the initials of a name with dashes.
For example,
John Smith, I should get JS
The regular expressions I have is the following:
name.match(/(^SS?|bS)?/g).join("").match(/(^S|S$)?/g).join("").toUpperCase()
However, it does not pick the correct inital for the last name. For example:
John Andrew-Smith, I should get JA
However, I get JS.
Why does it pick up the letter after dash, I am a bit confused.
Any help is much appreciated
EDIT: Sorry forgot to add this part, I should ignore any middle name initials. For example, John Andrew Smith, should be JS, not JAS. As Andrew would be considered a middle name
If the last name has dash, then it is part of the lastname, so Andrew-Smith, would be the last name
3
I would first split on spaces to get all initials in an array. Then join first and last elements from this array. So something like:
const allInitials = name.split(" ").map(n => n[0])
const initials = allInitials[0] + allInitials.splice(-1)
If you really want to use a regex, and do the above in one line you could do:
name.split(" ").map(n => n[0]).join("").replace(/^(.).*(.)$/g, "$1$2")
Silly me! The whole thing can just be:
name.replace(/^(.).*s(.).*$/, "$1$2")
Basically, capture 1st initial, then greedy ignore all characters up to last whitespace character, then capture the next character, and then ignore all characters up to end of string
4
I would use /(?<!-)[A-Z]/g
const names = [
'John Smith',
'John Andrew-Smith'
]
for (const name of names) {
const initials = name.match(/(?<!-)[A-Z]/g).join('')
console.log(name, initials)
}
4
A more straightforward approach using regex would be:
- match the first uppercase letter in a capture group
([A-Z])
- then any other word characters
w+
- then a space
s
- then another uppercase letter in a capture group
([A-Z])
- and then any other word characters
w+
^([A-Z])w+s([A-Z])w+
Though as mentioned in the comments, regex is overkill for something like this.
var getInitials = function(name) {
return name.match(/^([A-Z])w+s([A-Z])w+/).splice(1, 2).join("");
}
console.log(getInitials("John Smith"));
console.log(getInitials("John Andrew-Smith"));
You can try this:
const text = 'John Andrew Smith'
let result = /^(S)S+/g.exec(text)[1] + /(S)S+$/g.exec(text)[1];
document.write(result);
Because you said you don’t want to match the middle name I decided to first match the first letter of the first word then concat it with the first letter of the last word.
/^(S)S+/g
: Matches the first letter of a word from the beginning.
/(S)S+$/g
: Matches the first letter of a word from the ending.