I have code that is trying to take a full name like Marie Carrie Smith or Stan Alan Blan Baker and change it to Marie C. Smith - Stan A. B. Baker. I am missing a lot and feel like I could go about doing this a better way but for some reason I am suck and cannot get pass this.
module.export = {
@param {string} name
@return {string}
answer: function(name) {
var splitName = name.split(" ");
for (i=0; i<splitName.length; i++) {
if(splitName.length === 3) {
splitName[1].charAt(1);
} else if (splitName.length === 4) {
splitName[1].charAt(1);
splitName[2].charAt(1);
}
}
return split.join(" ");
}
}
答案 0 :(得分:2)
You could just beautify your code a bit:
const [first, ...rest] = name.split(" ");
const last = rest.pop();
return [first, ...rest.map(n => n[0] + "."), last].join(" ");
答案 1 :(得分:1)
You can use this little snippet:
module.export = {
@param {string} name
@return {string}
answer: function(name) {
return name.split(" ").map((val, index, arr) => (index !== 0 && index !== arr.length-1) ? val.charAt(0) + '.' : val).join(" ");
}
}
or if you're supporting ES6:
answer: name => name
.split(" ")
.map((val, index, arr) =>
(index !== 0 && index !== arr.length-1) ?
val.charAt(0) + '.' :
val)
.join(" ")
答案 2 :(得分:0)
Here is an example how you can do that a little bit easier
var name1="Marie Carrie Smith";
var name2="Stan Alan Blan Baker";
function answer(name) {
var splitName = name.split(" ");
if(splitName.length>=3){
for (i=1; i<splitName.length-1; i++) {
splitName[i]=splitName[i].charAt(0)+'.';
}
}
return splitName.join(" ")
}
console.log(answer(name1))
console.log(answer(name2))
module.export = {
@param {string} name
@return {string}
answer: function(name) {
var splitName = name.split(" ");
if(splitName.length>=3){
for (i=1; i<splitName.length-1; i++) {
splitName[i]=splitName[i].charAt(0)+'.';
}
}
return splitName.join(" ")
}
}