英文:
Get initials of names in Javascript
问题
我有个人名和组名
个人:
Robert Smith
David Smith
James Johnson
William
如果我使用这段代码
if(Name.split("",").length === 1)
return Name.trim().split("" ").map(x => x[0]).reduce((acc, curr) => acc + curr)
else
return ''
输出是
- RS
- DS
- JJ
但在我的第二种情况下,有一组名字
像
Robert Smith,David Smith
James Johnson,Robert Smith
在这种情况下,如果找到逗号,我想在第一种情况下返回RD
,在第二种情况下返回JS
。
英文:
I have Person and group names
> Person :
Robert Smith
David Smith
James Johnson
William
if i use this code
if(Name.split(",").length === 1)
return Name.trim().split(" ").map(x => x[0]).reduce((acc, curr) => acc + curr)
else
return ''
Output is
- RS
- DS
- JJ
but in my second scenario there are sets of names
like
Robert Smith,David Smith
James Johnson,Robert Smith
in this case if any comma is found i want to return RD
in first case and in second case JS
答案1
得分: 0
在第一个情景中,获取第一个和最后一个名字的首字母,并在第二个情景中获取每个名字的首字母。
请检查以下解决方案,
const scenario1 = "Robert Smith";
const scenario2 = "Robert Smith,David Smith";
function getInitial(data) {
const chunks = data.split(",");
if (chunks.length > 1) {
const initials = [];
chunks.forEach(chunk => initials.push(chunk[0]));
return initials.join('');
} else {
const [fname, lname] = chunks[0].split(' ');
return `${fname[0]}${(lname ? lname[0] : '')}`;
}
}
console.log(getInitial(scenario1))
console.log(getInitial(scenario2))
这段代码可以在第一个情景中获取名字的首字母,第二个情景中获取每个名字的首字母。
英文:
Your question is not clear, I assume you need to get the initial of the first and last name in the first scenario and get the initial of each name in the second scenario.
Check whether the following solution helps,
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const scenario1 = "Robert Smith";
const scenario2 = "Robert Smith,David Smith";
function getInitial(data) {
const chunks = data.split(",");
if ( chunks.length > 1) {
const initials = [];
chunks.forEach(chunk => initials.push(chunk[0]));
return initials.join('');
} else {
const [fname, lname] = chunks[0].split(' ');
return `${fname[0]}${(lname ? lname[0] : '')}`;
}
}
console.log(getInitial(scenario1))
console.log(getInitial(scenario2))
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论