/  Technology   /  Reverse a string in JavaScript
Reverse a string in JavaScript

Reverse a string in JavaScript

 

Reverse String is an operation in which the original string provided by the user is modified in such a way that the characters in it are arranged in reverse order starting from the last character to the first character, resulting in a new string that is the inverse of the original.

Step1: Check the input string so that if it is empty, has only one character, or is not of string    type, it returns “Not Valid string.”

Step2: If the previous condition is false, we can create an array to store the result. revArray[] is the new array in this case.

Step3: Loop through the array from beginning to end, pushing each item in the array revArray[].

Step4: To join the elements of an array into a string, use the JavaScript prebuilt function join().

 Reverse a string.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Reverse a string</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="newtab.css">
</head>
<body class="middle">
    <script>
            function ReverseString(str) {
                // Check input valid or not based on length 
                if(!str || str.length < 2 ||
                        typeof str!== 'string') {
                    return 'Not valid';
                }
                // Take empty array revArray
                const revArray = [];
                const length = str.length - 1;
                // Looping from the end
                for(let i = length; i >= 0; i--) {
                    revArray.push(str[i]);
                }
                // Joining the array elements
                return revArray.join('');
            }
            document.write(ReverseString("SAI"))
            </script>
    </script>
</body>
</html> 

newtab.css:

*{
    margin: 0px;
    padding:0px;
}
body{
    background-image: url('refresh.jpg');
    background-repeat: no-repeat;
    width:100%;
    background-size: cover;
}
.middle{
    margin-top: 27%;
    margin-left: 50%;
}

Output:

Reverse a string in JavaScript

 

Leave a comment