function - How can i convert to upper case manually ?(Javascript) - Stack Overflow

I am trying to write a function which returns the string value to uppercase with out the toUpperCase()

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();

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();
Share Improve this question edited Aug 13, 2017 at 23:11 Dij 9,8184 gold badges20 silver badges35 bronze badges asked Aug 13, 2017 at 23:11 Jesus MacJesus Mac 331 silver badge2 bronze badges 9
  • What do you mean by with out the toUpperCase() built in function? Are you looking for something to replace toUpperCase with? If so, why? – Fotis Commented Aug 13, 2017 at 23:14
  • 2 why? why? why? why? – vol7ron Commented Aug 13, 2017 at 23:14
  • What is the charset? English letters a to z? – Aydin4ik Commented Aug 13, 2017 at 23:15
  • I am trying to do it manually @Fotis – Jesus Mac Commented Aug 13, 2017 at 23:16
  • 1 Use .charCodeAt string method and lookup/research the difference between upper and lower case latin alphabet characters. Will I write it for you, no way. Do I think it will be worth it? – traktor Commented Aug 13, 2017 at 23:17
 |  Show 4 more ments

9 Answers 9

Reset to default 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);

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Ê

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!"));

  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)

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?

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 :)

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>

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 puter 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

You can always use a giant switch statement.

Even if its pletely 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));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745381330a4625240.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信