javascriptcharuppercaselowercase

Convert uppercase string to lowercase string in JS manually


Trying to write a function which returns the calling string value converted to lowercase. The trick is I can't use toLocaleLowerCase().

Below is what I have so far.

function charChange(char){
    for (var i=0; i<char.length; i++){
        var char2=charCodeAt(char[i])+32;
        var char3=String.fromCharCode(char2);
        if (char3 !== charCodeAt(97-122){
            alert("Please enter only letters in the function")
        }
    }
    return char;
}

Solution

  • To convert the uppercase letters of a string to lowercase manually (if you're not doing it manually, you should just use String.prototype.toLowerCase()), you must:

    1. Write the boilerplate function stuff:

      function strLowerCase(str) {
          let newStr = "";
          // TODO
          return newStr;
      }
      
    2. Loop over each character of the original string, and get its code point:

      function strLowerCase(str) {
          let newStr = "";
          for(let i = 0; i < str.length; i++) {
              let code = str.charCodeAt(i);
              // TODO
          } return newStr;
      }
      
    3. Check if the character is an uppercase letter. In ASCII, characters with code points between 65 and 90 (inclusive) are uppercase letters.

      function strLowerCase(str) {
          let newStr = "";
          for(let i = 0; i < str.length; i++) {
              let code = str.charCodeAt(i);
              if(code >= 65 && code <= 90) {
                  // TODO
              } // TODO
          } return newStr;
      }
      
    4. If the character is uppercase, add 32 to its code point to make it lowercase (yes, this was a deliberate design decision by the creators of ASCII). Regardless, append the new character to the new string.

      function strLowerCase(str) {
          let newStr = "";
          for(let i = 0; i < str.length; i++) {
              let code = str.charCodeAt(i);
              if(code >= 65 && code <= 90) {
                  code += 32;
              } newStr += String.fromCharCode(code);
          } return newStr;
      }
      
    5. Test your new function:

      strLowerCase("AAAAAAABBBBBBBCCCCCZZZZZZZZZaaaaaaaaaaa&$*(@&(*&*#@!");
      // "aaaaaaabbbbbbbccccczzzzzzzzzaaaaaaaaaaa&$*(@&(*&*#@!"