Open In App

How to process each letter of text using JavaScript ?

Given a string and the task is to process it character by character. 

string.toUpperCase()
string.charAt(index)

Example 1: This example processes the string letter by letter using for loop and converts each letter to uppercase separately. 






<!DOCTYPE HTML>
<html>
    <head>
        <title>
            How to process each character of text
        </title>
    </head>
     
    <body style = "text-align:center;">
     
        <h1 style = "color:green;" >
            GeeksForGeeks
        </h1>
     
        <p id = "GFG_UP" style =
            "font-size: 15px; font-weight: bold;">
        </p>
 
         
        <button onclick = "gfg_Run()">
            check
        </button>
         
        <p id = "GFG_DOWN" style =
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
 
         
        <script>
            var el_up = document.getElementById("GFG_UP");
            var el_down = document.getElementById("GFG_DOWN");
            var str = "This is String";
            el_up.innerHTML = "String = '"+str + "'";
         
            function gfg_Run() {
                var str_Upper = "";
                for (var i = 0; i < str.length; i++) {
                    str_Upper += str.charAt(i).toUpperCase();
                }
                el_down.innerHTML = str_Upper;
            }        
        </script>
    </body>
</html>                   

Output: 



Example 2: This example processes the string letter by letter using for in loop and alerts each letter separately. 




<!DOCTYPE HTML>
<html>
    <head>
        <title>
            How to process each letter of text
        </title>
    </head>
     
    <body style = "text-align:center;">
     
        <h1 style = "color:green;" >
            GeeksForGeeks
        </h1>
     
        <p id = "GFG_UP" style =
            "font-size: 15px; font-weight: bold;">
        </p>
 
         
        <button onclick = "gfg_Run()">
            check
        </button>
         
        <script>
            var el_up = document.getElementById("GFG_UP");
            var str = "str";
            el_up.innerHTML = "String = '" + str + "'";
         
            function gfg_Run() {
                for (var i in str) {
                    alert(" character = "+str.charAt(i));
                }
            }        
        </script>
    </body>
</html>                   

Output: 


Article Tags :