-3

I am trying to write a function which returns the string value to uppercase with out the toUpperCase() built-in function example ("hello"); returning "HELLO"

with out this:

var x="hello"
var y=x.toUpperCase();
Dij
  • 9,761
  • 4
  • 18
  • 35
Jesus Mac
  • 33
  • 1
  • 2

9 Answers9

5

One option is to hard code the characters. Use .indexOf() to match the character at adjacent property value of an object.

const map = {
  uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  lowercase: "abcdefghijklmnopqrstuvwxyz"
};

var x = "hello"
var y = x.replace(/(.)/g, match => map.uppercase[map.lowercase.indexOf(match)]);

console.log(y);
guest271314
  • 1
  • 15
  • 104
  • 177
4

Here is a function that does it (very old-school and manual) :

  • Loop through the string
  • If you encounter a lower case character, in other words, if you are at a character whose ASCII code is in the range [97,122], which is the range of the lower case alphabet characters, subtract 32 from it's ASCII code, because the difference between a lower case alpha-char and it's upper case form in ASCII is 32, then add it to a new string.
  • Else, add the character as is.


And as @georg, who is German (German alphabets include accented letters) pointed out, I added an update to include them.
Their range is [224,255], and the difference between each one and its upper-case form is also 32, so, no need for an else if :

function myToUpperCase(str) {
  var newStr = '';
  for (var i=0;i<str.length;i++) {
    var thisCharCode = str[i].charCodeAt(0);
    if ((thisCharCode>=97 && thisCharCode<=122)||(thisCharCode>=224 && thisCharCode<=255)) {
     newStr += String.fromCharCode(thisCharCode - 32);
    } else {
     newStr += str[i];
    }
  }
  return newStr;
}
console.log(myToUpperCase('helLo woRld!')); // => HELLO WORLD!
console.log(myToUpperCase('üñïçødê')); // => ÜÑÏÇØDÊ
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • 1
    Old school indeed! How about this string : `"üñïçødê"`? – georg Aug 13 '17 at 23:44
  • First, Old-school means it's almost the first thing you study (one of the basics of CS) and a must know function. Second, nobody is talking about accented alphabets, at least the OP should've mentioned'em. – DjaouadNM Aug 13 '17 at 23:50
  • @georg thank you anyway, I updated the code based on your proposition. – DjaouadNM Aug 14 '17 at 00:02
  • 1
    Thanks. Your improvement is quite naive, but that's better than completely ignoring unicode issues (unfortunately, still a common mistake among english-speaking programmers). – georg Aug 14 '17 at 00:06
  • You know, in fact I'm Arab (which is weird because our alphabet is way weirder then yours), I just deal with English-speaking programmers all the time, which is why the accented characters problem didn't occur to me. – DjaouadNM Aug 14 '17 at 00:13
  • ***This is why re-inventing the wheel is dangerous.*** All though this solution (and most of those on this page, including mine) deal perfectly with normal characters, none seem to cope well with accented characters - **unlike** `.toUpperCase()`, which does. – Toastrackenigma Aug 14 '17 at 00:15
  • One should only use user-defined functions in special cases which the predefined functions don't cover. – DjaouadNM Aug 14 '17 at 00:20
3

you can use x.charCodeAt(0) - 32 to convert a char to small letters and String.fromCharCode to convert a ascii code to character. Use split() to get individual characters and map() to access and convert each character and join() to form back a string. something like this seems to work:

function capitalize(str){
  var arr = str.split("");
  arr = arr.map(x => {
     var charCode = x.charCodeAt(0);
     return charCode>=97 && charCode<=122 ? String.fromCharCode(charCode - 32) : x;
   });
  return arr.join("");
}

console.log(capitalize("hello!"));
Dij
  • 9,761
  • 4
  • 18
  • 35
1
  1. Create templates arrays $lower = ["a", "b"...] , $upper = ["A", "B"]
  2. split example word example.split("")
  3. Iterate trough all letters (example) and get indexes of the letters from $lower
  4. Use indexes to get letters from $upper
  5. join the upper case letters

It's raw procedure of what I would do trying to do something like You. But remember the worst thing You can do is to "invent" a wheel again, so just use built-in function (it's faster)

kinny94
  • 376
  • 1
  • 5
  • 22
John Tribe
  • 1,407
  • 14
  • 26
0

I think that toUpperCase is well optimised to convert from various charsets but if you'd like to write your own replacement, you could be using .charCodeAt so for example

function myToUpperCase(str) {
 return str.split("").map(function (chr) {
   var chrCode = chr.charCodeAt(0);
   // Return non a-z chars as they are
   if ( chrCode > 122 || chrCode < 97)
     return chr;
   return String.fromCharCode(chrCode - 32);
 }).join("");
}

What I'm doing here:

  • Splitting the string into an array of chars
  • Return invalid input as-is
  • Getting the char code from each letter
  • The difference from a lowercase to uppercase character is 32
  • Join the chars into a new string

Just my 2 cents :)

Fotis
  • 1,322
  • 16
  • 30
0

This is a bad idea

ALWAYS use a built-in method whenever possible. There is no reason to re-invent the wheel, when other people have already reliably made and tested it for years.

However...

You could change the ASCII codes of some letters to do this. All characters on a computer are represented by numeric codes, so by converting to this code (either ASCII or Unicode), performing a numeric operation, and then converting back, we can transform the case of letters.

You can find a table of all ASCII codes here.

function newToUpperCase(text) {
  var result = ""; //Store the new text
  for (var i=0;i<text.length;i++) { //Loop through all characters in the string
    var code = text[i].charCodeAt(0) //Get the ASCII code of the current character
    if (code>=97&&code<=122) { //If it is a lower-case letter (code is between 97 and 122 inclusive) 
      code -= 32; //Subtract 32 from the code to make it the code for an uppercase letter
    }
    result += String.fromCharCode(code); //Concatenate the character code transformed to a string to the result
  }
  return result; //Return the result
}

document.write(newToUpperCase("This is a test!")) //Test the function
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55
  • For some procedures there is no built-in method. – guest271314 Aug 13 '17 at 23:33
  • @guest271314 That's why I said *whenever possible*. In many cases (such as this one) there is a built-in method. Here it is `.toUpperCase()`. – Toastrackenigma Aug 13 '17 at 23:33
  • fwiw [How to filter Object using Array.prototype.filter?](https://stackoverflow.com/questions/36232576/how-to-filter-object-using-array-prototype-filter), [Why is there not a built-in method in JavaScript to check if an object is a plain object?](https://stackoverflow.com/questions/40456491/why-is-there-not-a-built-in-method-in-javascript-to-check-if-an-object-is-a-plai), [How to call function that is parameter to Function.prototype.bind with value passed as parameter to Function.prototype.bind](https://stackoverflow.com/q/40541169/) – guest271314 Aug 13 '17 at 23:39
  • @guest271314 I am aware that there are lots of cases when there are no built-in functions that do what you need. My answer even states this: "ALWAYS use a built-in method **whenever possible**", "There is no need to re-invent the wheel, **when** other people have already reliably made and tested it". In cases where such a function does not exist, yes you have to build it yourself. **This is not one of those cases**, and when a built-in method exists it is usually best practice to use it. – Toastrackenigma Aug 13 '17 at 23:44
0

You can rely on ANSI code, lower case characters range from 65-90, upper case characters are in 97-122. There for: UPPERCASE = LOWERCASE - 32;

<input type="text" id="my_text_source" placeholder="MM/dd/YYYY" />
<input type="text" id="my_text_result" placeholder="MM/dd/YYYY" />
<input type="button" id="my_button" value="To Uppercase">

<script>
    var myButton = document.querySelector('#my_button');

    myButton.onclick = function (evt) {
        var myTextSource = document.querySelector('#my_text_source');
        var source = myTextSource.value;
        var result = "";
        for (var i=0; i<source.length; i++) {
            // convert lower case characters to uppercase.
            if (source.charCodeAt(i) >= 97 && source.charCodeAt(i) <= 122) {
                result += String.fromCharCode(source.charCodeAt(i) - 32);
            }
            // otherwise, leave as is.
            else {
                result += source[i];
            }
        }

        var myTextResult = document.querySelector('#my_text_result');
        myTextResult.value = result;
    };
</script>
Khoa Bui
  • 733
  • 1
  • 7
  • 15
0
var upperize = 
    str => str.replace( /[a-z]/g, c=>String.fromCharCode(c.charCodeAt(0)-32));

console.log( upperize( "hello Folks !@# 42") );

After multiple responses with code, I'll present another version using regular expressions. Because the method calls three different string andString methods, it will be less efficient than the built in .toUpperCase string method. Writing replacements for built in methods is unlikely to provide improvment.

As an exercise, what changes would be needed to make the code above convert upper case 'A' through 'Z' to lower case?

traktor
  • 17,588
  • 4
  • 32
  • 53
-3

You can always use a giant switch statement.

Even if its completely unreasonable to do so.

function toUpperCaseSwitch(value){
 switch(value) {
case 'a':
    return 'A'
    break;
case 'b':
    return 'B'
    break;
case 'c':
    return 'C'
    break;
case 'd':
    return 'D'
    break;
case 'e':
    return 'E'
    break;
case 'f':
    return 'F'
    break;
case 'g':
    return 'G'
    break;
case 'h':
    return 'H'
    break;
case 'i':
    return 'I'
    break;
case 'j':
    return 'J'
    break;
case 'k':
    return 'K'
    break;
case 'l':
    return 'L'
    break;
case 'm':
    return 'M'
    break;
case 'n':
    return 'N'
    break;
case 'o':
    return 'O'
    break;
case 'p':
    return 'P'
    break;
case 'q':
    return 'q'
    break;
case 'r':
    return 'R'
    break;
case 's':
    return 'S'
    break;
case 't':
    return 'T'
    break;
case 'u':
    return 'U'
 case 'v':
    return 'V'
    break;
case 'w':
    return 'W'
    break;
case 'x':
    return 'X'
    break;
case 'y':
    return 'Y'
    break;
case 'z':
    return 'Z'
default:
    return value;
}


};

function toUpperCaseLoop(string){
        if(!string || string.length <1){
                return "";
        }
    var returnString = "";
    for(var i = 0; i < string.length; ++i){
            var val = toUpperCaseSwitch(string[i]);
            if(val){
            returnString = returnString + toUpperCaseSwitch(string[i]);
                }
        }
        return returnString;

}

var test = "hello World";

 console.log(toUpperCaseLoop(test));
Community
  • 1
  • 1
camccar
  • 690
  • 12
  • 24