admin管理员组

文章数量:1332394

I have a string and need to turn it to uppercase using map function. It would be something like this:

var str = 'hello world how ya doing?';
function toUpperCase(str){
  return str.split('').map((v,i) =>  i%2 == 0 ? v[i].toLowerCase(): v[i].toUpperCase()).join('');
 }

console.log(toUpperCase(str));

I have a string and need to turn it to uppercase using map function. It would be something like this:

var str = 'hello world how ya doing?';
function toUpperCase(str){
  return str.split('').map((v,i) =>  i%2 == 0 ? v[i].toLowerCase(): v[i].toUpperCase()).join('');
 }

console.log(toUpperCase(str));

But when I run it I get entire sentence in uppercase.

Share Improve this question edited Apr 4, 2017 at 13:13 kind user 41.9k8 gold badges68 silver badges78 bronze badges asked Apr 4, 2017 at 10:41 OunknownOOunknownO 1,2064 gold badges22 silver badges41 bronze badges 2
  • Please show your actual code. That one throws an error, it doesn't turn the entire sentence uppercase. – JJJ Commented Apr 4, 2017 at 10:44
  • @OunknownO you should change your question title to 'every second character of the word'. – Mamun Commented Apr 4, 2017 at 11:04
Add a ment  | 

4 Answers 4

Reset to default 6

v argument holds actually every single letter inside the array, so using v[i] has no sense.

var str = 'hello world how ya doing?';

function toUpperCase(str) {
  return str.split('').map((v, i) => i % 2 == 0 ? v.toLowerCase() : v.toUpperCase()).join('');
}

console.log(toUpperCase(str));

I guess you meant to turn upperCase every second letter, but if you really care about whole word:

var str = 'hello world how ya doing?';

function toUpperCase(str) {
  return str.split(' ').map((v, i) => i % 2 == 0 ? v.toLowerCase() : v.toUpperCase()).join(' ');
}

console.log(toUpperCase(str));

Try the following:

var str = 'hello world how ya doing?';
var res = str.split(' ').map(function(v,i){
    return i%2 === 0 ? v.toLowerCase():v.toUpperCase()
});
console.log(res.join(' '));

You're reading a single char from your array's value.

The parameter val of .map(function(val, i) will be every single string in your array of words. I fixed your code, I hope it will clear to you:

var str = 'hello world how ya doing?';

console.log(toUpperCase(str));

function toUpperCase(str){
  var words = str.split(' ');
  var uppers = words.map(function(val, i) {
    if(i%2 == 0)
      return (val + "").toLowerCase();
    else
      return (val + "").toUpperCase();
  });
  return uppers.join(' ');
}

Split the given string in the array then Use Array.prototype.map(),

then you can convert every second character using toUpperCase() function.

Have a look at below code:

 "hello world how ya doing"
      .split("")
      .map((s, i) => (i % 2 != 0 ? s.toUpperCase() : s))
      .join("");

    OUTPUT: "hElLo wOrLd hOw yA DoInG"

本文标签: javascriptTurn every second character to uppercase using mapStack Overflow