简体   繁体   中英

how can I change the form of alphabet in this string?

I want to make string 'hello' to 'hElLo' which is only even number in the index changes to capital letters.

Source code:

function toWeirdCase(s){
 var str = s.split(''); // var str = {'h','e','l','l','o'}
 for(var i = 0; i<str.length; i++){
    if(str.length[i]%2===0){
        return str.toUpperCase();
    }
   }
  }

console.log(toWeirdCase('hello'))

But the result is undefined

You can do something like:

 function toWeirdCase(s) { var str = s.split(''); // var str = {'h','e','l','l','o'} for (var i = 0; i < str.length; i++) { if (i % 2 !== 0) { //Test the index and not the letter //Since the goal is to capitalized the odd numbers (array starts at 0). You can use the condition i % 2 !== 0. This means the index reminder is not 0. str[i] = str[i].toUpperCase(); //Assign the value } } return str.join(''); //Join the array and return } console.log(toWeirdCase('hello')) 

You can use replace with a regex to convert to uppercase each letter having an odd index:

 function toWeirdCase(s) { return s.replace(/./g, (m, i) => i % 2 ? m.toUpperCase() : m); } console.log(toWeirdCase('hello')); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM