JS by Exercise 001 – Explanation

First we create  a function called my input

function myinput() {
}

Now we need to capture the input of the user with the prompt command

  let myInp = prompt("Please enter your phrase");

Now that that we have an input from the user consisting in several words we can split this string using the split function and a space (” “) as a delivemeter. We do that by defining a variable x which is an array and we fill it by splitting the string by ” ” and measure how many elements are in the array using length

let x= myInp.split(" ");
let lenarr = x.length;

The following section of the JS code is the one that does the job. First we define 2 variables mystring and total. Both of those variable are type String.

Then we start looping through the array variable x and pass each single word to a variable called myword

So if we have given 3 words as input separated by a space (” “) now we will generate a loop where myword will receive each single word as the loop continues.

Here is any example if we pass the input: javascript is fun.

Now variable x will be composed by an Array of 3 elements.

Now that we have any array we can loop through it. Each single element of the array is passed to the myword variable.

For each word we measure the length again and we start a second loop.

In this second loop we concatenate from char #2 to to the last char (myword.length) and then we add the the first letter (which for java is char[0] by the way)

Then we add the string “ou” and a space char.

let mystring="";
let total="";
    for (i=0;i<lenarr;i++)  {
        var myword=x[i];
        for (y=0;y<x[i].length;y++) {
          mystring= myword.slice(1,myword.length) + myword.slice(0,1) + "ou" + " ";
        }

        total = total + mystring  

So if the input is :

The output by moving the first letter and the end of each word and adding “ou” is:

Here is the full code available to everyone 

function myinput() {
    let myInp = prompt("Please enter your phrase");
    document.getElementById("yourinput").innerHTML="Input->:" + myInp;

    let x= myInp.split(" ");
    let lenarr = x.length;

    let mystring="";
    let total="";
    for (i=0;i<lenarr;i++)  {
        var myword=x[i];
        for (y=0;y<x[i].length;y++) {
          mystring= myword.slice(1,myword.length) + myword.slice(0,1) + "ou" + " ";
        }

        total = total + mystring   
        
    }
    total ="Output->:" + total;
    document.getElementById("yourresult").innerHTML=total;   

One thought on “JS by Exercise 001 – Explanation”

Leave a Reply

Your email address will not be published. Required fields are marked *