These are the two most elegant solutions I can think of (at the moment). See comments within the code and don't hesitate to ask if anything is unclear.
function charChange1 (str) {
let result = '';
const len = str.length;
// go over each char in input string...
for (let i = 0; i < len; i++) {
const c = str[i];
const charCode = c.charCodeAt(0);
if (charCode < 65 || charCode > 90) {
// if it is not a uppercase letter,
// just append it to the output
// (also catches special characters and numbers)
result += c;
} else {
// else, transform to lowercase first
result += String.fromCharCode(charCode - 65 + 97);
}
}
return result;
}
function charChange2 (str) {
// Array.prototype.slice.call(str) converts
// an array-like (the string) into an actual array
// then, map each entry using the same logic as above
return Array.prototype.slice.call(str)
.map(function (c) {
const charCode = c.charCodeAt(0);
if (charCode < 65 || charCode > 90) return c;
return String.fromCharCode(charCode - 65 + 97);
})
// finally, join the array to a string
.join('');
}
console.log(charChange1("AAAAsfasSGSGSGSG'jlj89345"));
console.log(charChange2("AAAAsfasSGSGSGSG'jlj89345"));
(On a side node, it would of course be possible to replace the magic numbers by constants declared as calls to 'A'.charCodeAt(0))
(A second side node: Don't use char since it is a reserved word in JavaScript; I prefer c)
.toLowerCase()?charis a reserved word in JS that you are not allowed to use. Ifcharis an array (which it looks like), it should bechars.charCodeAt(97-122)becomescharCodeAt(-25), which makes no sense becauseString.prototype.charCodeAt()(1) must be called on a string and (2) takes an index, not a code point.charCodeAtis a method, not a function! You might want to dochar[i].charCodeAt(0)instead ofcharCodeAt(char[i])