mh108
11/26/2018 - 8:02 PM

P4 String Machine code

P4 String Machine code

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <meta http-equiv="X-UA-Compatible" content="ie=edge" />
      <link rel="stylesheet" href="str-machine.css" />
      <title>String Machine</title>
   </head>
   <body>
      <h2><img src="strings.jpg" alt="" />String Machine</h2>
      <p>Enter a String: <input id="inBox" size="50" type="text" /></p>
      <p>
         <button id="b1">Length</button> &nbsp; <button id="b2">Reverse</button>
      </p>
      <div></div>
      <script src="str-machine.js"></script>
   </body>
</html>
// jshint esversion: 6

//helper functions

//one of 10 ways to reverse a string, from p. 131 J:ABG.
let reverseStr = (s) => {
   return s
      .split('')
      .reverse()
      .join('');
};

//recognizer for vowels
let isVowel = (s) => {
   let vowels = /[aeiouy]/i;
   return vowels.test(s);
};

//returns the number of vowels in word
let countVowels = (word) => {
   let count = 0;
   //count vowels
   for (let i = 0; i < word.length; ++i) {
      if (isVowel(word.charAt(i))) {
         ++count;
      }
   }
   return count;
};

//recognizer for digits
let isDigit = (s) => {
   let digits = /\d/i;
   return digits.test(s);
};

//returns the number of digits in word
let countDigits = (word) => {
   let count = 0;
   //count vowels
   for (let i = 0; i < word.length; ++i) {
      if (isDigit(word.charAt(i))) {
         ++count;
      }
   }
   return count;
};

//1. Define a dispatcher to handle all button clicks
var main = function() {
   //get the value entered by the user
   let str = document.querySelector('input').value;

   //the "this" keyword is set to the button that was clicked
   console.log(this.id);

   //dispatch function on button id
   if (this.id == 'b1') {
      //display the length of the string
      document.querySelector('div').innerHTML = 'Length = ' + str.length;
   } else if (this.id == 'b2') {
      //display the reverse of the string
      document.querySelector('div').innerHTML = 'Reverse = ' + reverseStr(str);
   } else if (this.id == 'b3') {
      $('div').innerHTML = 'You clicked Button 3';
   } else if (this.id == 'b4') {
      $('div').innerHTML = 'You clicked Button 4';
   }
};

//2. Register the onclick handler for each button after the DOM is complete
window.addEventListener('load', () => {
   //select the buttons
   var buttons = document.querySelectorAll('button');

   //register the same handler for each button
   for (var i = 0; i < buttons.length; ++i) {
      buttons[i].addEventListener('click', main);
   }
});