Change string based on a condition - JavaScript


We are required to write a JavaScript function that takes in a string. The task of our function is to change the string according to the following condition −

  • If the first letter in the string is a capital letter then we should change the full string to capital letters.
  • Otherwise, we should change the full string to small letters.

Example

Following is the code −

const str1 = "This is a normal string";
const str2 = "thisIsACamelCasedString";
const changeStringCase = str => {
   let newStr = '';
   const isUpperCase = str[0].charCodeAt(0) >= 65 && str[0].charCodeAt(0) <= 90;
   if(isUpperCase){
      newStr = str.toUpperCase();
   }else{
      newStr = str.toLowerCase();
   };
   return newStr;
};
console.log(changeStringCase(str1));
console.log(changeStringCase(str2));

Output

Following is the output in the console −

THIS IS A NORMAL STRING
thisisacamelcasedstring

Updated on: 15-Sep-2020

615 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements