Skip to content

Instantly share code, notes, and snippets.

@ontiuk
Last active August 20, 2016 13:37
Show Gist options
  • Select an option

  • Save ontiuk/6b2fec83a65adf8a8f9968df76f51c51 to your computer and use it in GitHub Desktop.

Select an option

Save ontiuk/6b2fec83a65adf8a8f9968df76f51c51 to your computer and use it in GitHub Desktop.
Get case / type of a string's character by position in Javascript
<script>
function charType(chr, pos) {
pos = (pos === undefined) ? 0 : parseInt(pos);
var ret = "O";
var code = chr.charCodeAt(pos);
if (code >= "A".charCodeAt(0) && code <= "Z".charCodeAt(0)) {
return "U";
} else if (code >= "a".charCodeAt(0) && code <= "z".charCodeAt(0)) {
return "L";
} else if (code >= "0".charCodeAt(0) && code <= "9".charCodeAt(0)) {
return "N";
}
return '';
}
//Usage - string & position (0 index)
var str = "Hello World!";
var pos = 0;
switch (charType(str,pos)) {
case "U":
document.write("Character " + str[pos] + " is upper case");
break;
case "L":
document.write("Character " + str[pos] + " is lower case");
break;
case "N":
document.write("Character " + str[pos] + " is a number");
break;
default:
document.write("Character " + str[pos] + " is not a character or a number");
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment