Skip to content

Instantly share code, notes, and snippets.

@georgioupanayiotis
Last active August 29, 2015 14:16
Show Gist options
  • Save georgioupanayiotis/f7981b52a6d9203a6acb to your computer and use it in GitHub Desktop.
Save georgioupanayiotis/f7981b52a6d9203a6acb to your computer and use it in GitHub Desktop.
Automatically Convert String to Upper Case with Javascript
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function changeEach(el){
var text = document.getElementById(el).value;
var capital = text.toUpperCase();
document.getElementById(el).value = capital;
}
function capitalize(e) {
var t = '"@.,”/!?%^&*=+<>|`~-_(){}[]#;:“0123456789';
var n = "";
var r = 0;
e: for (var i = 0; i < e.length; i++) {
for (var s = 0; s < t.length; s++) {
var o = e.charCodeAt(i);
if (o >= 65 && o <= 90 || o >= 97 && o <= 122) {
r = i;
break e;
}
}
}
if (r == 0) {
n = e.charAt(0).toUpperCase() + e.substring(1, e.length);
} else {
n = e.substring(0, r) + e.charAt(r).toUpperCase() + e.substring(r + 1, e.length - r + 1);
}
return n;
}
function firstLetter(id) {
var e = document.getElementById(id).value;
var t = "";
var n = "";
for (var r = 0; r < e.length; r++) {
var i = e.charCodeAt(r);
if (i == 32 || i == 10) {
if (n != "") {
t += capitalize(n) + (i == 10 ? "<br/><br/>" : " ");
n = "";
continue;
}
n = "";
} else {
if (n == "") {
n += e.charAt(r).toUpperCase();
} else {
n += e.charAt(r).toLowerCase();
}
}
}
t += capitalize(n) + " ";
document.getElementById(id).value = t;
}
</script>
<style type="text/css">
li{
list-style: none;
}
</style>
<title>Automatically Change Text to Upper Case</title>
</head>
<body>
<div id="container">
<ul>
<h1>Change Each Letter to Upper Case</h1>
<li>
<input id="efname" type="text" name="efname" onChange="changeEach(this.id);" placeholder="First Name...">
<input id="elname" type="text" name="elname" onChange="changeEach(this.id);" placeholder="Last Name...">
</li>
<h1>Change First Letter of Each Word to Upper Case</h1>
<li>
<input id="ffname" type="text" name="ffname" onChange="firstLetter(this.id);" placeholder="First Name...">
<input id="flname" type="text" name="flname" onChange="firstLetter(this.id);" placeholder="Last Name...">
</li>
</ul>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment