Wednesday, August 26, 2020

JavaScript : string.toUpperCase(), Make uppercase first letter of each word with in a variable

I want to make the first letter of each word upper case with in a variable. I have tried the JavaScript String toUpperCase() Method to do like below:



<!DOCTYPE html>
<html>
<body>
<button onclick="convertToUpperCase()">Convert ToUpperCase</button>
<p id="convert"></p>
<script>
function convertToUpperCase() {
  var str = "Hello World!";
  var res = str.toUpperCase();
  document.getElementById("convert").innerHTML = res;
}
</script>
</body>
</html>


I have not satisfied with above code. I have searched over the web, i found the solution at 'stackoverflow' as below:


<!DOCTYPE html>
<html>
<body>
<button onclick="convertToUpperCase()">Convert ToUpperCase</button>
<p id="solution"></p>
<script>
function convertToUpperCase() {
  var str = "hello world!";
  
  str=str.toLowerCase().replace(/\b[a-z]/g, function(letter){
      return letter.toUpperCase();
  });
  
  document.getElementById("solution").innerHTML = str;
}
</script>
</body>
</html>

This work's for me.

No comments:

Post a Comment