...

View Full Version : JavaScript String to uppercase and lowercase???



zk0
02-22-2007, 04:07 PM
Hi,

I want to create the following output:


Kalle Anka
kALLE aNKA
K#lle #nka

I know how to create "Kalle Anka" and "K#lle #nka".

But how do I do to change the lowercase letters to uppercase and the uppercase letters to lowercase? :confused:



Kalle Anka
kALLE aNKA :confused:
K#lle #nka


THANKS!

BarrMan
02-22-2007, 04:17 PM
urstring.toLowerCase();
urstring.toUpperCase();

shyam
02-22-2007, 07:13 PM
function swapCase(ch) {
return /[a-z]/.test(ch) ? ch.toUpperCase() : ch.toLowerCase();
}
str = 'Kalle Anka';
arr = str.split('');
trans_str = arr.map(swapCase).join('');

zk0
02-22-2007, 07:16 PM
urstring.toLowerCase();
urstring.toUpperCase();

Hi "BarrMan"!

Thanks, but I already know that (Maybe I should have written that?).

I need to know how to implement this in my code so that "Kalle Anka" becomes "kALLE aNKA".

Maybe using a for or if statement?

Thoughts, ideas and tips are welcomed! :thumbsup:

shyam
02-22-2007, 07:20 PM
oh and in case u want to run it in IE use a for/while loop instead of the map sorta like


for ( i = 0; i < arr.length; i++ ) {
arr[i] = swapCase(arr[i]);
}

zk0
02-22-2007, 07:38 PM
Thanks "shyam"! :thumbsup:


return /[a-z]/.test(ch) ? ch.toUpperCase() : ch.toLowerCase();

Can you please explain your code? Im very new to javascript and would like to know how it all works. :)

BarrMan
02-22-2007, 07:41 PM
If I'm not wrong, the function checks if each letter of the string is in lowercase (a-z), if the character is in lowercase - make it uppercase, else make it lowercase.

statement ? result1 : result2
This is a short of:

if(statement)
result1
else
result2

Philip M
02-22-2007, 08:04 PM
This question was answered recently by Vic Phillips

http://www.codingforums.com/showthread.php?t=107641

shyam
02-22-2007, 08:05 PM
return /[a-z]/ (http://www.devguru.com/Technologies/ecmascript/QuickRef/regexp.html).test(ch) ? ch.toUpperCase() : ch.toLowerCase();
putting stuff between /'s is short-hand for the getting a RegExp (http://www.devguru.com/Technologies/ecmascript/QuickRef/regexp.html) object and [a-z] matches only the lowercase characters as u've already guessed by now and BarrMan has explained the ternary operator too :)... so, there u go



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum