w3resource

JavaScript: Switch case of the minimum possible number of letters to make a given string written in the upper case or in the lower case

JavaScript Basic: Exercise-98 with Solution

Write a JavaScript program to switch case of the minimum possible number of letters to make a given string written in the upper case or in the lower case.

Fox example "Write" will be write and "PHp" will be "PHP"

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title> Switch case of the minimum possible number of letters to make a given string written in the upper case or in the lower case</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function change_case(new_str) {
  var x = 0;
  var y = 0;

  for (var i = 0; i < new_str.length; i++) {
    if (/[A-Z]/.test(new_str[i])) {
      x++;
    } else y++;
  }

  if (y > x) return new_str.toLowerCase();
  return new_str.toUpperCase();
}

console.log(change_case("Write"))
console.log(change_case("PHp"))

Sample Output:

write
PHP

Flowchart:

Flowchart: JavaScript - Switch case of the minimum possible number of letters to make a given string written in the upper case or in the lower case

ES6 Version:

function change_case(new_str) {
  let x = 0;
  let y = 0;

  for (let i = 0; i < new_str.length; i++) {
    if (/[A-Z]/.test(new_str[i])) {
      x++;
    } else y++;
  }

  if (y > x) return new_str.toLowerCase();
  return new_str.toUpperCase();
}

console.log(change_case("Write"))
console.log(change_case("PHp"))

Live Demo:

See the Pen javascript-basic-exercise-98 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Write a JavaScript program to find the shortest possible string which can create a string to make it a palindrome by adding characters to the end of it.
Next: Write a JavaScript program to check whether it is possible to rearrange characters of a given string in such way that it will become equal to another given string.

What is the difficulty level of this exercise?



JavaScript: Tips of the Day

Parameter's value

function getItems(fruitList, ...args, favoriteFruit) {
  return [...fruitList, ...args, favoriteFruit]
}

getItems(["banana", "apple"], "pear", "orange")

...args is a rest parameter. The rest parameter's value is an array containing all remaining arguments, and can only be the last parameter! In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error.

function getItems(fruitList, favoriteFruit, ...args) {
  return [...fruitList, ...args, favoriteFruit];
}


getItems(['banana', 'apple'], 'pear', 'orange');
The above example works. This returns the array [ 'banana', 'apple', 'orange', 'pear' ].

Ref: https://bit.ly/3jFRBje