Link to home
Start Free TrialLog in
Avatar of tbathgate
tbathgate

asked on

Problem with Javascript function

Dear All,

I am having problems with the following function. The function is supposed to take a sting of 'Ab' and return it back as 'aB' Instead this function for some reason is returning the string as 'aBb' I know that it is returning part of the original string but I have had no luck whats so ever in fixing this. Can aonyone help me spot the error. the code is as follows:

function isLowerCase(aCharacter)

/*
* Function returns true if its single-character string
* argument is a lowercase alphabetic character.
* Required for implementation of reverseCase.
*/

{
      return (aCharacter >= 'a') && (aCharacter <= 'z')
}



function reverseCase(aString)

/*
* Function returns
* a new string which has the same
* characters as aString except that all
* lowercase characters are replaced by
* their uppercase equivalents, and all
* uppercase characters are replaced by
* their lowercase equivalents.
*/

{
      var newString;       //the string to be returned

      newString = '';      //initialise the string to be returned
      for (var index = 0; index < aString.length; index = index + 1)
      {
            if (isLowerCase(aString.charAt(index)))
            {
                  newString = newString + aString.charAt(index).toUpperCase()
            }
            
                  newString = newString + aString.charAt(index).toLowerCase()
            
      };
      return newString
}


Many Thansk to anyone who can help!!


ASKER CERTIFIED SOLUTION
Avatar of Batalf
Batalf
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tbathgate
tbathgate

ASKER

Thanks all for the speedy and most helpful responses. I can't believe  I was silly enough to forget the else statement(I am only just learning javascript to explain my simple mistake)!!!! I suppose the saying a fresh pair of eyes is very true!!!

Thanks Again

Tom
Avatar of Zvonko
You can forget the "else" statement.
Check this:

<script>

function strInvert(theStr){
  return theStr.replace(/\w/g,function(p){return(p<"a")?p.toLowerCase():p.toUpperCase()});
}


alert(strInvert("  aB cD "));


</script>