Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
How to add toAlternatingCase custom method to String class in 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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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).

about 4 years ago · Juan Pablo Isaza Report

0

String.prototype.toAlternatingCase = function () {
  return this.split("").map(l => l === l.toUpperCase() ? l.toLowerCase() : l.toUpperCase()).join("");
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!