Skip to content

Instantly share code, notes, and snippets.

@mudge
Created November 7, 2008 14:57
Show Gist options
  • Save mudge/22878 to your computer and use it in GitHub Desktop.
Save mudge/22878 to your computer and use it in GitHub Desktop.
JavaScript function to replicate Ruby's "succ()" method.
String.prototype.succ = function() {
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
var result = '';
for (var i = 0; i < this.length; i++) {
if (alphabet.indexOf(this.charAt(i).toLowerCase()) != -1) {
if (this.charAt(i).isUpperCase()) {
result += alphabet.charAt(
alphabet.toUpperCase().indexOf(this.charAt(i)) + 1).toUpperCase();
} else {
result += alphabet.charAt(alphabet.indexOf(this.charAt(i)) + 1);
}
} else {
result += this.charAt(i);
}
}
return result;
};
String.prototype.isUpperCase = function() {
return this.toUpperCase() == this;
};
/*
* "a".succ() => "b"
* "b".succ() => "c"
* "C".succ() => "D"
* "def".succ() => "efg"
* "gHi".succ() => "hIj"
* "£$^".succ() => "£$^"
* "abc£$^".succ() => "bcd£$^"
* "c".isUpperCase() => false
* "C".isUpperCase() => true
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment