获取JavaScript中的名称首字母

huangapple go评论60阅读模式
英文:

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 ''

输出是

  1. RS
  2. DS
  3. JJ

但在我的第二种情况下,有一组名字

  1. Robert Smith,David Smith
  2. 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

  1. RS
  2. DS
  3. JJ

but in my second scenario there are sets of names

like

  1. Robert Smith,David Smith
  2. 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 = &quot;Robert Smith&quot;;
const scenario2 = &quot;Robert Smith,David Smith&quot;;

function getInitial(data) {

  const chunks = data.split(&quot;,&quot;);
  
  if ( chunks.length &gt; 1) {
    const initials = [];
    chunks.forEach(chunk =&gt; initials.push(chunk[0]));
    return initials.join(&#39;&#39;);
  } else {
    const [fname, lname] = chunks[0].split(&#39; &#39;);
    return `${fname[0]}${(lname ? lname[0] : &#39;&#39;)}`;
  }

}

console.log(getInitial(scenario1))
console.log(getInitial(scenario2))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月8日 22:16:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定