вот более javascript ориентированный подход:
var initials = fullNames.map(fullname => {
return fullname
.replace(/^(?:Mr|Miss|dr|lord)\.? ?/, '') // remove title
.split(' ')
.map(substring => substring[0].toUpperCase())
.join('')
.substring(0, 2) // this part is to match only 2 chars
});
// => [ 'BS', 'JB', 'TW', 'LS', 'LK' ]
Вы можете удалить часть .substring(0, 2)
, если у вас все в порядке с 'dr Lisa S pink' === LSP
const fullNames = [
"Mr Bob Smith",
"Miss Jessica Blue",
"tim white",
"dr Lisa S pink",
"lord Lee Kensington-Smithe"
]
const initials = fullNames.map(fullname => {
return fullname
.replace(/^(?:Mr|Miss|dr|lord)\.? ?/, '')
.split(' ')
.map(substring => substring[0].toUpperCase())
.join('')
.substring(0, 2)
})
const initialsV2 = fullNames.map(fullname => {
return fullname
.replace(/^(?:Mr|Miss|dr|lord)\.? ?/, '')
.split(' ')
.map(substring => substring[0].toUpperCase())
.join('')
})
$('#initials').html(fullNames.map( (fullName, i) => `${fullName.padEnd(28, ' ')} => ${initials[i]}` ).join('\n'))
$('#initials2').html(fullNames.map( (fullName, i) => `${fullName.padEnd(28, ' ')} => ${initialsV2[i]}` ).join('\n'))
V1 only 2 letters
V2 any letters length