I'm working on a challenge that takes in a string, then returns the string in all caps, a few replacements/substitutions for vowels, and has "!!!!" after each word.
function gordon(a){
return a.split(" ").map(function(x){return x.replace(/[aA]/g,"@").replace(/[aeiou]/g,"*") + "!!!! ";}).join("").toUpperCase();
}
This code works, and returns the right answer, except for ONE whitespace at the end of the last "!!!".
The main reason I'm asking this is because this is something that I feel like I run into a lot with the map method or for loops. What do you do if you want to affect all elements except the last one? Is there an easy way to acplish this?
I'm working on a challenge that takes in a string, then returns the string in all caps, a few replacements/substitutions for vowels, and has "!!!!" after each word.
function gordon(a){
return a.split(" ").map(function(x){return x.replace(/[aA]/g,"@").replace(/[aeiou]/g,"*") + "!!!! ";}).join("").toUpperCase();
}
This code works, and returns the right answer, except for ONE whitespace at the end of the last "!!!".
The main reason I'm asking this is because this is something that I feel like I run into a lot with the map method or for loops. What do you do if you want to affect all elements except the last one? Is there an easy way to acplish this?
Share Improve this question edited Sep 27, 2016 at 22:03 Heretic Monkey 12.1k7 gold badges61 silver badges131 bronze badges asked Sep 27, 2016 at 21:50 newmannewman 4213 gold badges9 silver badges26 bronze badges 5- Try using reduce instead of map – Rastalamm Commented Sep 27, 2016 at 21:51
- 1 I don't see where the extra whitespace is ing from. Does the input string have a space at the end? Try trimming it before you split it. – Barmar Commented Sep 27, 2016 at 21:54
- @Rastalamm I tried using reduce and it is only returning the first element in the array as the answer with all the "!!!" behind it. – newman Commented Sep 27, 2016 at 21:58
- @barmar My mistake! I edited my code with the whitespace. I need white space after each returned word, but not on the LAST word. Thats the issue I'm running into... – newman Commented Sep 27, 2016 at 22:00
-
1
map
takes a callback function. That function takes three parameters, the current value, the index, and the array. You should be able to deduce from the last two whether you are on the last element or not. – Heretic Monkey Commented Sep 27, 2016 at 22:02
1 Answer
Reset to default 5Since you want space between the words after joining, put that in the .join()
call instead of after !!!!
.
function gordon(a){
return a.split(" ")
.map(function(x){
return x.replace(/[aA]/g,"@").replace(/[aeiou]/g,"*") + "!!!!";
})
.join(" ")
.toUpperCase();
}
The argument to .join()
is the separator put between each array element when they're concatenated into the result string.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744782220a4593409.html
评论列表(0条)