skip to Main Content

(for example asdfghjkl to AsDfGhJkL).

function toWeirdCase(string){
  var chars = string.toLowerCase().split("");
  for (var i = 0; i < chars.length; i += 2) {
    chars[i] = chars[i].toUpperCase();
  }
  return chars.join("");
};

I tried this but it does not account for the spaces between the character. How can I set it to ignore spaces?

3

Answers


  1. You can split a string into an array and alternate the case based on the index:

    const toWeirdCase = str => [...str].map((char, idx) => idx % 2 ? char.toLowerCase() : char.toUpperCase()).join('');
    
    console.log(toWeirdCase('asdfghjkl'));
    Login or Signup to reply.
  2. Add an additional check within the for loop to skip spaces.

    function toWeirdCase(string) {
      var chars = string.toLowerCase().split("");
      for (var i = 0; i < chars.length; i += 2) {
        if (chars[i] !== ' ') { // Check if the character is not a space
          chars[i] = chars[i].toUpperCase();
        }
      }
      return chars.join("");
    }
    

    Here, before converting a character to uppercase, it first checks if the character is not a space (‘ ‘). If it’s a space, it skips the conversion and moves on to the next character. This ensures that spaces are ignored while alternating the case of the string.

    Now, when call the toWeirdCase function with a string, it will alternate the case of characters while ignoring spaces.

    console.log(toWeirdCase("asdfghjkl")); // Output: "AsDfGhJkL"
    console.log(toWeirdCase("hello world")); // Output: "HeLlO WoRlD"
    

    Note: The updated function assumes that you want to ignore spaces while alternating the case of alphabetic characters. If you also want to ignore other non-alphabetic characters, you can modify the condition in the if statement accordingly.

    Hope this help you.

    Login or Signup to reply.
  3. There are multiple ways to do it.

    One thing you can do is adding to your loop this condition :

    function toWeirdCase(string){
      var chars = string.toLowerCase().split("");
      for (var i = 0; i < chars.length; i += 2) {
        if(chars[i] === ' ') {
          i--;
          continue
        }
        chars[i] = chars[i].toUpperCase();
      }
      return chars.join("");
    };
    

    That way if there is a space the loop will continue to iterate.

    i-- is to go to the next index after the space (we decrement i because i – 1 + 2 correspond to the next index). That is if you want the space not to count in the alternation between uppercase and lowercase

    If you want the space to count in the alternation between uppercase / lowercase, you can just do continue

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search