(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
You can split a string into an array and alternate the case based on the index:
Add an additional check within the
for
loop to skip spaces.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.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.
There are multiple ways to do it.
One thing you can do is adding to your loop this condition :
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 decrementi
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 lowercaseIf you want the space to count in the alternation between uppercase / lowercase, you can just do
continue