Commonly Used JavaScript Objects: Math and String Methods

3. String Methods and Properties

3.1. An example on using String Properties and Methods


          Let’s say that you are given a programming problem of replacing all the vowels in a given string with underscores and all consonants must be converted to uppercase. The code below is one way to solve this problem.


<!DOCTYPE html>
<html>
  <head>
   <title>Page Title</title>
  </head>
  <body>
    <script>
     var name = "Uzumaki Naruto";
     function solveProblem(name){
       name = name.toUpperCase(); /* change all characters to uppercase */
       for(i=0; i<name.length; i++){
          /* test each character if it is a vowel */
           if (name[i]=="A" || name[i]=="E" || name[i]=="I" || name[i]=="O" || name[i]=="U")
          {
                  name = name.replace(name[i], "_"); /* replacing vowel with _ */
           } 
        }
        window.alert(name);
     }
     solveProblem(name)  /* call the function in order for it execute */
    </script>
  </body>
</html>

Input: Uzumaki Naruto 
Output: _Z_M_K_ N_R_T_


NOTE: Replacing the statement in the code sample above name = name.replace(name[i], "_"); with name[i] = "_"; will not work because of string immutability. Refer to the given link for further explanations regarding string immutability: https://medium.com/@codesprintpro/javascript-string-immutability-ead81df30693

          For a complete list of String Properties and Methods, you can visit this link here (https:// www.w3schools.com/jsref/jsref_obj_string.asp).