首页 > 代码库 > WeIrD StRiNg CaSe

WeIrD StRiNg CaSe

Description:

Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.

The passed in string will only consist of alphabetical characters and spaces(‘ ‘). Spaces will only be present if there are multiple words. Words will be separated by a single space(‘ ‘).

Examples:

toWeirdCase( "String" );//=> returns "StRiNg"
toWeirdCase( "Weird string case" );//=> returns "WeIrD StRiNg CaSe"

解题:

function write(string){
var nstr=‘‘;
var result=‘‘;
var n=‘‘;
    string.split(‘ ‘).forEach(function(items,index){
           items.split(‘‘).forEach(function(item ,index){
              nstr +=(index % 2 == 0 ? item.toUpperCase() : item.toLowerCase());
          });
       result += nstr + ‘ ‘;
     })
   console.log(result);
    result.split(‘ ‘).forEach(function(item,index){    
              console.log(item+‘,‘+result.split(‘ ‘)[index-1]);      
              n+= item.replace(result.split(‘ ‘)[index-1],‘ ‘);
   })
     return n;
}
write(‘This is a test‘); 

大神解法:

function toWeirdCase(string){
  return string.split(‘ ‘).map(function(word){
    return word.split(‘‘).map(function(letter, index){
      return index % 2 == 0 ? letter.toUpperCase() : letter.toLowerCase()
    }).join(‘‘);
  }).join(‘ ‘);
}

少了两层循环 ,我还是js函数用的少

function toWeirdCase(string){
  return string.replace(/(\w{1,2})/g,(m)=>m[0].toUpperCase()+m.slice(1))
}

这....

function toWeirdCase(string) {
  var i = 0;
  return [].map.call(string.toLowerCase(), function(char) {
    if (char == " ") { i = -1; }
    return i++ % 2 ? char : char.toUpperCase();
  }).join(‘‘);
}
function toWeirdCase(string){
  return string.split(/ /g).map(function (word) { return word.split(‘‘).map(function (c, i) { return i % 2 ? c.toLowerCase() : c.toUpperCase(); }).join(‘‘) }).join(‘ ‘);
}

都能明白,也没啥高深的东西 ,方法多解要多练

WeIrD StRiNg CaSe