Javascript .toLowerCase/.toUpperCase in mixed mode

2k views Asked by At

I try to code some function. I want to change every 2nd letter .toUpperCase. I get it to work with str.char[0].toUpperCase but have to do it with the whole char numbers manually (char[0],char[1],char[2]) and so on.

Can someine help me out with an array which transforms a given string like this: teststring to: tEsTsTrInG.

My problem is to built an array which takes every second letter of given string and changes it .toUpperCase.

4

There are 4 answers

0
elclanrs On

You can do it with this obscene regex:

var str = 'teststring';

str = str.replace(/(.)(.)/g, function(_,a,b){
  return a + b.toUpperCase();
});

console.log(str); //=> tEsTsTrInG
0
MarcoL On

You can see a JS string as an "array" like structure:

function toCamelCase(string){
  // if passed a null string
  if(!string){
    return '';
  }
  var newString = '';
  for( var c = 0; c < string.length; c++){

    newString += c % 2 ? string[c].toLowerCase() : string[c].toUpperCase();

  }
  return newString;
}
0
Andrew On

See this:

function convert(str)
{
    str = str.split('');
    for(var i=0, len=str.length;i<len;i++)
    {
       if(i%2)str[i] = str[i].toUpperCase();
    }
    return str.join('');
}

http://jsfiddle.net/rooseve/sf3PR/

0
Rewind On

How about

// Returns string
function fancyString(arg){
    var ret, low, upp, i;
    low = arg.toLowerCase();
    upp = arg.toUpperCase();
    for(i=0,ret="";i<arg.length;i++){
        ret += (i%2)===0 ? low[i] : upp[i];
    }
    return ret;
};