如何转换未确定数量的输入字符串?

问题描述 投票:0回答:3

我正在编写一些代码来转换一些输入名称(例如:John Doe - > J. Doe)而不知道输入名称的长度(可能是John Williams Roger Fred Doe,那将是J. W. R. F. Doe)。

我想出了2个名字输入的算法,但我找不到有效的方法来覆盖其余的案例。我想到的唯一方法是将其余案例包含在一些if语句中最多10个名称。还有其他有效的方法吗?提前致谢!

function convertName(name) {
    var [a, b] = name.split(" ");
    var c = `${a[0]}${". "}${b}`;
    return c;
    }
javascript
3个回答
1
投票

我想你想要这样的东西:

function convertName(name) {
    const nameArray = name.split(" ")

    return nameArray
        .map((name, index) => index !== nameArray.length - 1 ? `${name[0]}.` : name)
        .join(' ')
}

这里发生了什么?

  • .map()迭代一个数组并返回一个新数组,它可以采用1或2个args,项目和索引(按此顺序)Array.map()
  • index !== nameArray.length - 1我们确保它不是索引中的最后一项,因为你想要那个整体
  • ? ${name[0]}.如果它不是最后一项,则截断
  • : name如果是的话,把它全部留下来
  • .join(' ')将数组.map()返回,返回单个字符串

这个函数不关心名称中有多少个部分,它还处理单个部分名称,即:"John Snow The One" => "J. S. T. One""John" => "John"


0
投票

您可以使用pop()删除姓氏。然后map()将其余部分转换为姓名缩写。最后把它们放在一起:

function convertName(name) {
    var names = name.trim().split(" ");
    let last = names.pop()
    return [...names.map(s => s[0]), last].join(". ")
}
console.log(convertName("John Williams Roger Fred Doe"))
console.log(convertName("John Doe"))
console.log(convertName(" Doe"))

您可能想要检查单个名称等边缘情况。


0
投票

你可以做这样的事情,它很容易理解。

function convertName(name) {

    var arrayNames = name.split(" ");  // Create an array with all the names

    // loop on all the name except the last one
    for (var i = 0; i < arrayNames.length - 1; i++) { 

        arrayNames[i] = arrayNames[i].charAt(0).concat(".") // Keeping the first letter and add the dot
    }

    return arrayNames.join(" "); // join all the array with a ' ' separator
}

console.log(convertName("John Williams Roger Fred Doe"))
console.log(convertName("John Doe"))
© www.soinside.com 2019 - 2024. All rights reserved.