简体   繁体   中英

How to convert an undetermined number of input Strings?

I'm writing some code to convert some input names(ex: John Doe -> J. Doe) without knowing the length of the inputted name(could be John Williams Roger Fred Doe, that would be JWRF Doe).

I figured out the algorithm for the 2 names input but I can't find an efficient way to cover the rest of the cases. The only way that comes to my mind is wrapping the rest of the cases up to 10 names in some if statements. Is there any other efficient way to do it? Thanks in advance!

function convertName(name) {
    var [a, b] = name.split(" ");
    var c = `${a[0]}${". "}${b}`;
    return c;
    }

I think you want something like this:

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

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

What is happening here?

  • .map() iterates an array and returns a new one, it can take 1 or 2 args, the item and index (in that order) Array.map()

  • index !== nameArray.length - 1 we make sure it is not the last item in the index because you want that whole

  • ? ${name[0]}. if it's not last item, then truncate

  • : name if it is, leave it whole
  • .join(' ') turns the array .map() returns, back into a single string

This function does not care how many parts there are in a name, and it also handles single part names ie: "John Snow The One" => "JST One" while "John" => "John"

You can use pop() to remove the last name. Then map() to convert the rest to initials. In the end put it all together:

 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")) 

You might want to check for edge cases like single names.

You could make something like this, it simple to understand.

 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")) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM