Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add toAlternatingCase custom method to String class in JavaScript?

Tags:

javascript

I'm trying to add a custom method to the String class in JavaScript called toAlternatingCase, it will turn lowercase characters into uppercase and vice versa in the string that is called on, I'm trying to make it like the built-in toUpperCase/toLowerCase methods which don't take any arguments. this is a kata(challenge) on codewars.


1 Answers

This can be done by utilizing the prototype method to extend the String class. This probably isn't the most efficient way of doing this, but it can be achieved with something like this:

String.prototype.toAlternatingCase = function() {
  var ns = "";
  for(var i = 0; i < this.length; i++) ns += (this.slice(i, i+1) == this.slice(i, i+1).toUpperCase()) ? this.slice(i, i+1).toLowerCase() : this.slice(i, i+1).toUpperCase();
  return ns;
}

"String.prototype.toAlternatingCase".toAlternatingCase();
// Should return 'sTRING.PROTOTYPE.TOaLTERNATINGcASE'

This just loops through the string and reverses the case of each character, then returns that new result (without modifying the original string).

like image 88
EssXTee Avatar answered Apr 16 '26 14:04

EssXTee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!