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();
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) :
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!"));
$lower = ["a", "b"...] , $upper = ["A", "B"]
example.split("")
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)
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:
Just my 2 cents :)
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.
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
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>
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?
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));