Ultimate Java Script Cheat Sheet

JavaScript is a very important language to learn for Hackers. So, thats why, we are here to provide you a base in JavaScript.

Firstly, we are going to build some programming base for our Aspirant Hackers. The most important skills for any Hacker is the programming skills he/she possesses. You are going to need a lot of programming in your Hacking Career for developing your own tools or finding some vulnerability in the code of any website or software.

Today, we are going to continue our JavaScript tutorials series. As a Hacker, I cannot forget the impact of JavaScript as a Skill for Hackers. Its a must especially for those who want to learn Web Hacking. And remember that “2016 is Javascript” no matter if you are a programmer or Hacker.

Javascript is rapidly moving towards Server Side Scripting, and it will soon become a major Client Side and Server Side Technology for Web Development. That’s another good reason to learn Javascript right now.

Today, I realized that I should also post a CheatSheet for JavaScript. It will help you to brush up your JavaScript concept every time you feel like getting frustrated in JavaScript. So, here it is. But, before diving into the code, make sure to watch the video along with this code.

The Ultimate Javascript CheatSheet:-

Here is the Ultimate Javascript CheatSheet :-

The Ultimate JavaScript CheatSheet

JavaScript

  

    

    

    

      body {font-size: 1.6em;}

      .hidden {display:none;}

      .show {display:inline !important;}

      button {

        border: 2px solid black; background:#E5E4E2;

        font-size: .5em; font-weight: bold; color:black;

        padding: .8em 2em;

        margin-top: .4em;

      }

    

  

  

  

  

  // You create variables that store values with var

  // Prompt opens a popup that requests info

  var yourName = prompt(“What is your name?”);

  // If performs different actions depending on conditions

  if(yourName != null){

    // Set text in an HTML element with the id sayHello

    // You concatenate (combine) strings with +

    document.getElementById(“sayHello”).innerHTML = “Hello “ + yourName;

  } else {

    // Alert opens a popup that contains a message

    alert(“Please Enter Your Name Next Time”);

  }

// ———- VARIABLES ———-

// variable names can’t start with a number, contain spaces, but can

// contain letters, numbers, underscores or $ (Are case sensitive)

var myName = “Webster”;

var myAge = 18;

// Variables don’t have a defined type, which can cause problems

myName = 100;

// ———- MATH ———-

// document.write outputs data to the browser

document.write(“5 + 4 = “, 5 + 4, “
”);

// Using + instead of , will treat everything as a string unless you use ()

document.write(“5 + 4 = “ + (5 + 4) + “
”);

document.write(“5 – 4 = “, 5 – 4, “
”);

document.write(“5 * 4 = “, 5 * 4, “
”);

document.write(“5 / 4 = “, 5 / 4, “
”);

// Modulus remainder of a division

document.write(“5 % 4 = “, 5 % 4, “
”);

var maxNum = Number.MAX_VALUE;

document.write(“Max Num = “, maxNum,“
”);

document.write(“Min Num = “,Number.MIN_VALUE, “
”);

// Numbers have 16 digits of precision

precisionTest = 0.1000000000000001;

document.write(precisionTest +0.1000000000000001, “
”);

// Round number to 2 decimal places

var balance = 1563.87;

document.write(“Monthly payment : “,(balance / 12).toFixed(2), “
”);

var randNum = 5;

// Shortcut for adding 1

document.write(“randNum++ = “,randNum++, “
”);

document.write(“++randNum = “,++randNum, “
”);

// The same exists for –

document.write(“randNum– = “, randNum—,“
”);

document.write(“–randNum = “, —randNum,“
”);

// Perform a calculation on a value and assign the result

document.write(“randNum += 5 = “, randNum+= 5, “
”);

document.write(“randNum -= 5 = “, randNum-= 5, “
”);

document.write(“randNum *= 5 = “, randNum*= 5, “
”);

document.write(“randNum /= 5 = “, randNum/= 5, “
”);

// Order of operations

document.write(“3 + 2 * 5 = “, 3 + 2 * 5,“
”);

document.write(“(3 + 2) * 5 = “, (3 + 2) * 5,“
”);

// Math properties and methods

document.write(“Math.E = “, Math.E, “
”);

document.write(“Math.PI = “, Math.PI,“
”);

document.write(“Math.abs(-8) = “,Math.abs(–8), “
”);

document.write(“Math.cbrt(1000) = “,Math.cbrt(1000), “
”);

document.write(“Math.ceil(6.45) = “,Math.ceil(6.45), “
”);

document.write(“Math.floor(6.45) = “,Math.floor(6.45), “
”);

document.write(“Math.round(6.45) = “,Math.round(6.45), “
”);

document.write(“Math.log(10) = “,Math.log(10), “
”); // Natural log

document.write(“Math.log10(10) = “,Math.log10(10), “
”); // Base 10 log

document.write(“Math.max(10,5) = “,Math.max(10,5), “
”);

document.write(“Math.min(10,5) = “,Math.min(10,5), “
”);

document.write(“Math.pow(4,2) = “,Math.pow(4,2), “
”);

document.write(“Math.sqrt(1000) = “,Math.sqrt(1000), “
”);

document.write(“Random # (1-10) = “,Math.floor((Math.random() * 10) + 1),“
”);

// Convert strings to numbers

document.write(“Converted String : “,Number(“3.14”), “
”);

document.write(“Converted Int : “,parseInt(“5”), “
”);

document.write(“Converted Float : “,parseFloat(“5.555”), “
”);

// ———- STRINGS ———-

var randStr = “A long “ + “string that “ + “goes on and on”;

// String length

document.write(“String Length : “,randStr.length + “
”);

document.write(“Index for \”goes\” : “,randStr.indexOf(“goes”), “
”);

// Return the value using a start and end index

document.write(randStr.slice(19, 23) +“
”);

// Return everything after the start index

document.write(randStr.slice(19) + “
”);

// Return the value using the start index and length

document.write(randStr.substr(19, 4) +“
”);

// Replace a string

document.write(randStr.replace(“and on”,“forever”) + “
”);

// Get character at an index

document.write(“At Index 2 : “,randStr.charAt(2) + “
”);

// Split a string into an array

var randStrArray = randStr.split(” “);

// Trim white space

randStr = randStr.trim();

// Convert to uppercase

document.write(randStr.toUpperCase() +“
”);

// Convert to lowercase

document.write(randStr.toLowerCase() +“
”);

// Styling with JS

var strToStyle = “Random String”;

document.write(“Big : “, strToStyle.big(), “
”);

document.write(“Bold : “, strToStyle.bold(),“
”);

document.write(“Font Color : “,strToStyle.fontcolor(“blue”), “
”);

document.write(“Font Size : “,strToStyle.fontsize(“8em”), “
”);

document.write(“Italics : “,strToStyle.italics(), “
”);

document.write(“Google : “,strToStyle.link(“http://google.com”), “
”);

document.write(“Small : “, strToStyle.small(),“
”);

document.write(“Strike : “, strToStyle.strike(),“
”);

document.write(“Sub : “, strToStyle.sub(),“
”);

document.write(“Sup : “, strToStyle.sup(),“
”);

// ———- CONDITIONALS ———-

// Relational Operators : == != > = = 5) && (age <= 6)){

  document.write(“Go to Kindergarten
”);

} else if (age > 18) {

  document.write(“Go to College
”);

} else {

  document.write(“Go to Grade “, age – 5,“
”);

}

document.write(“true || false = “, true || false,“
”);

document.write(“!true = “, ! true, “
”);

document.write(“\”5\” == 5 = “, (“5” == 5),“
”);

document.write(“\”5\” === 5 = “, (“5” === 5),“
”);

// Switch is used to match a limited number of options

switch(age) {

  case 5 :

  case 6 :

    document.write(“Go to Kindergarten
”);

    break;

  case 7 :

    document.write(“Go to 1st Grade
”);

    break;

  default :

    document.write(“Subtract 5 from your age
”);

}

// Ternary Operator assigns a value based on a condition

// (condition) ? iftrue : ifFalse

var canIVote = (age >= 18) ? true : false;

document.write(“Can I Vote : “, canIVote, “
”);

// ———- LOOPING ———-

// while loops as long as a condition is true

var i = 1;

while (i <= 10){

  document.write(i, “, “);

  i++;

}

document.write(“
”);

// do while is used when you must go through the loop at least once

do{

  var guess = prompt(“Guess a number between 1 and 20”);

}while(guess != 15)

alert(“You guessed it! 15 was the number”);

// for is a self contained looping structure

for(j = 0; j <= 20; j++){

  // If j is divisible by 2 then skip back to the top of the loop

  if((j % 2) == 0){

    continue;

  }

  // If j is equal to 15 break completely out of the loop

  if(j == 15){

    break;

  }

  document.write(j, “, “);

}

document.write(“
”);

var customer = {name : “Bob Thomas”,address : “123 Main”, balance : 50.50};

// for in cycles through an enumerable properties of an object

for(k in customer){

  document.write(customer[k], “
”);

}

// ———- ARRAYS ———-

// Arrays have variable sizes and can contain multiple types in JS

var tomSmith = [“Tom Smith”, “123 Main”,120.50];

// Access first array item

document.write(“1st State : “, tomSmith[0],“
”);

// Add an item

tomSmith[3] = “tsmith@abc.com”;

// Overwrite index 2 and fit everything else after index 2 without

// overwriting (Put 0 for second parameter to not overwrite)

tomSmith.splice(2, 1, “Pittsburgh”, “PA”);

// Delete the 4th index item

tomSmith.splice(4,1);

// Convert an array into a string (Also use toString())

document.write(“Array : “,tomSmith.valueOf(), “
”);

// Convert an array into a string with separator

document.write(“Array : “, tomSmith.join(“, “),“
”);

// Delete an index

delete tomSmith[3];

// Sort an array (reverse() for reverse sort)

// Works for sorting strings

tomSmith.sort();

// Sort numbers

var numbers = [4,3,9,1,20,43];

// Descending sort return y – x

numbers.sort(function(x,y){ return x – y });

document.write(“Num Array : “,numbers.toString(), “
”);

// Combine arrays

var combinedArray =numbers.concat(tomSmith);

// Remove the last item

tomSmith.pop();

// Add items to the end

tomSmith.push(“555-1212”, “US”);

// Deletes the first item

tomSmith.shift();

// Adds item to the first index

tomSmith.unshift(“Tom Smith”);

for (var i = 0; i < tomSmith.length; i++) {

  document.write(tomSmith[i], “
”);

}

// ———- FUNCTIONS ———-

// Functions provide code reuse and eliminate repetitive code

// Define a function that checks if a value is in an array

function inArray(arrayToCheck, value){

  for(i = 0; i < arrayToCheck.length; i++){

    if(arrayToCheck[i] === value){

      return true;

    }

  }

  return false;

}

var randArray = [1,2,3,4,5];

document.write(“In Array : “,inArray(randArray, 4), “
”);

// Local variables defined in functions can’t be accessed outside of

// the function

function times2(num){

  var var2 = 2;

  return num * var2;

}

// Causes Error : document.write(“Val of var2 : “, var2, “
”);

// Pass a function as a parameter

function times3(num){

  return num * 3;

}

function multiply(func, num){

  return func(num);

}

document.write(“3 * 15 = “, multiply(times3,15), “
”);

// Define a function expression

// We can assign functions to variables, store them in arrays,

// pass them into other functions and return them from functions

var triple = function(num){

  return num * 3;

};

document.write(“3 * 45 = “, multiply(triple,45), “
”);

// Receive variable number of arguments

function getSum(){

  var sum = 0;

  for(i = 0; i < arguments.length; i++){

    sum += arguments[i];

  }

  return sum;

}

document.write(“Sum : “, getSum(1,2,3,4,5),“
”);

// Return a variable number of values

function times2(theArray){

  var newArray = [];

  for(i = 0; i < theArray.length; i++){

    newArray.push(theArray[i] * 2);

  }

  return newArray;

}

document.write(“Array Doubled : “,times2([1,2,3,4,5]).toString(), “
”);

// Recursive Function

function factorial(num){

  if(num <= 1){

    return 1;

  } else {

    return num * factorial(num – 1);

  }

}

document.write(“Factorial of 4 : “,factorial(4), “
”);

// 1st: num = 4 * factorial(3) = 4 * 6 = 24

// 2nd: num = 3 * factorial(2) = 3 * 2 = 6

// 3rd: num = 2 * factorial(1) = 2 * 1 = 2

// ———- EVENT HANDLING ———-

function openAlert(mess){

  alert(mess);

}

// ———- DATE ———-

// Get a Date object

var curDate = new Date();

document.write(“Date : “, curDate.getDate(),“
”);

document.write(“Month : “,curDate.getMonth(), “
”);

document.write(“Day : “, curDate.getDay(),“
”);

document.write(“Year : “,curDate.getFullYear(), “
”);

document.write(“Time : “,curDate.getHours(), “:”, curDate.getMinutes(),

  “:”, curDate.getSeconds(), “:”,curDate.getMilliseconds(), “
”);

// Create a Date object for my birthday

var myBD = new Date(“December 21, 2015”);

var msForBD = myBD.getTime();

var timeNow = curDate.getTime();

var tilMyBD = msForBD – timeNow;

document.write(“Days till Birthday : “,tilMyBD / (1000 * 60 * 60 * 24), “
”);

Say Hello

SaySomething

Makeme Red

Key Data Here

Get Logo

Mouse X: 

Mouse Y: 

ClearInputs

function getChar(event) {

  // event.which returns the key or mouse button clicked

  if (event.which == null) {

    // Return the char if not a special character

    returnString.fromCharCode(event.keyCode); // IE

  } else if (event.which!=0 &&event.charCode!=0) {

    return String.fromCharCode(event.which);  // Other Browsers

  } else {

    return null; // Special Key Clicked

  }

}

document.getElementById(‘charInput’).onkeypress = function(event) {

  var char = getChar(event || window.event)

  if (!char) return false; // Special Key Clicked

  document.getElementById(‘keyData’).innerHTML = char + ” was clicked”;

  return true;

}

// Change text when the input gains focus

document.getElementById(‘charInput’).onfocus = function(event) {

  document.getElementById(‘keyData’).innerHTML = “Input Gained Focus”;

}

// Change text when the input loses focus

document.getElementById(‘charInput’).onblur = function(event) {

  document.getElementById(‘keyData’).innerHTML = “Input Lost Focus”;

}

// Change text when text is selected

document.getElementById(‘charInput’).onselect = function(event) {

  document.getElementById(‘keyData’).innerHTML = “Text Selected”;

}

// Add a listener that triggers a function on browser resize

window.addEventListener(“resize”,browserResized);

function browserResized() {

  document.getElementById(‘keyData’).innerHTML = “I’ve been resized”;

}

// Make image invisible on click

document.getElementById(‘logo’).onclick =function(event) {

  // Change the class for the image

  document.getElementById(‘logo’).className = “hidden”;

  // Change the input element value

  document.getElementById(‘mouseInput’).value = “Clicked on image with button “ +event.button;

}

// Make image visible on click

document.getElementById(‘logoButton’).onclick = function(event) {

  document.getElementById(‘logo’).className = “show”;

}

// Change image src on mouseover

document.getElementById(‘logo’).onmouseover = function(event) {

  document.getElementById(‘logo’).src = “ntt-logo-horz.png”;

  document.getElementById(‘mouseInput’).value = “Mouse Over image”;

}

// Change image src back on mouseout

document.getElementById(‘logo’).onmouseout = function(event) {

  document.getElementById(‘logo’).src = “ntt-logo.png”;

  document.getElementById(‘mouseInput’).value = “Mouse Left image”;

}

// Get mouse x y coordinates

document.body.onmousemove = function(e){

    e = e || window.event;

    // Get pageX, pageY : Mouse position relative to the html doc

    var pageX = e.pageX;

    var pageY = e.pageY;

    if (pageX === undefined) {

        // clientX, clientY : Mouse position relative to the browsers viewport

        // scrollLeft, scrollTop : Pixels an element is scrolled left or

        // from the top

        pageX = e.clientX +document.body.scrollLeft +document.documentElement.scrollLeft;

        pageY = e.clientY +document.body.scrollTop +document.documentElement.scrollTop;

    }

    document.getElementById(‘mouseX’).value = pageX;

    document.getElementById(‘mouseY’).value = pageY;

};

// Clear all input elements

document.getElementById(‘clearInputs’).onclick = function(event) {

  var inputElements =document.getElementsByTagName(‘input’);

  for (var i = 0; i < inputElements.length; i++) {

  if (inputElements[i].type == “text”) {

    inputElements[i].value = “”;

  }

}

}

Lorem ipsum dolor sit amet, consecteturadipiscing elit. Proin eget turpis eget quamluctus malesuada ut ac nulla. Suspendissefermentum magna neque, a auctor felispretium eget. Fusce ornare feugiat magna, utfaucibus sapien congue ut. Nunc nec fringillaex, nec varius nisl. Ut eget laoreet nisi.Aenean quis venenatis mauris, at volutpatante. Donec sollicitudin lacinia ornare. Inquis accumsan ligula, id egestas enim.

BackgroundColor

BackgroundImage

BorderStyle

BorderWidth

BorderColor

// Change background color

document.getElementById(‘chgBkColor’).onclick = function(event) {

  document.getElementById(‘sampDiv’).style.backgroundColor = “#EFDECD”;

}

// Change background image

document.getElementById(‘chgBkImg’).onclick = function(event) {

  document.getElementById(‘sampDiv’).style.backgroundImage =“url(‘repeatBkgrnd.png’)”;

}

// Change border style

document.getElementById(‘chgBorderStyle’).onclick = function(event) {

  document.getElementById(‘sampDiv’).style.borderStyle = “solid”;

}

// Change border width

document.getElementById(‘chgBorderWidth’).onclick = function(event) {

  document.getElementById(‘sampDiv’).style.borderWidth = “thick”;

}

// Change border color

document.getElementById(‘chgBorderColor’).onclick = function(event) {

  document.getElementById(‘sampDiv’).style.borderColor = “blue”;

}

Lorem ipsum dolorsit amet, consectetur adipiscingelit. Proin eget turpis eget quam luctusmalesuada ut ac nulla. Suspendissefermentum magna neque, a auctor felispretium eget. Fusce ornare feugiat magna, utfaucibus sapien congue ut. Nunc nec fringillaex, nec varius nisl. Ut eget laoreet nisi.Aenean quis venenatis mauris, at volutpatante. Donec sollicitudin lacinia ornare. Inquis accumsan ligula, id egestas enim.
Lorem ipsum dolor sit amet,consectetur adipiscing elit. Proineget turpis eget quam luctus malesuada utac nulla. Suspendisse fermentum magnaneque, a auctor felis pretium eget.Fusce ornare feugiat magna, utfaucibus sapien congue ut. Nunc necfringilla ex, nec varius nisl.

Go toGoogle

ForwardPage

Back Page

Reload Page

// Get current web page info

document.write(“Current URL : “,window.location.href, “
”);

document.write(“Current Host : “,window.location.hostname, “
”);

document.write(“Current Path : “,window.location.pathname, “
”);

// Change site on button click

document.getElementById(‘goToGoogle’).onclick = function(event) {

  window.location.href = “http://google.com”;

  // OR

  // window.location.assign(“http://google.com”);

}

// Go forward a page on click

document.getElementById(‘forwardPage’).onclick = function(event) {

  history.forward();

}

// Go back a page on click

document.getElementById(‘forwardPage’).onclick = function(event) {

  history.back();

}

// Use history.go(-2) or history.go(2) to jump multiple pages

// Reload page on button click

document.getElementById(‘reload’).onclick =function(event) {

  window.location.reload(true);

}

// You can get all ps and then target them like an array

var pElements =document.getElementsByTagName(‘p’);

pElements[3].style.backgroundColor =“#EFDECD”;

// Target the html

document.childNodes[1].style.backgroundColor = “#FAEBD7”;

// Change the color of the 1st child in sampDiv2

var sampDiv2 =document.getElementById(‘sampDiv2’);

sampDiv2.childNodes[0].style.backgroundColor = “#F0FFFF”;

// Style the 1st child of sampDivs 1st child

sampDiv2.childNodes[0].childNodes[1].style.backgroundColor = “#BFAFB2”;

// JavaScript can get confused by text nodes when targeting elements

// Text nodes are whitespace, which nodeType will identify with a 3

// while elements as a 1

// You can eliminate text nodes by deleting whitespace or by using a

// minimizer (lastChild and firstChild may not work)

document.write(“Node Type : “,sampDiv2.childNodes[0].childNodes[0].nodeType, “
”);

document.write(“Node Name : “,sampDiv2.childNodes[0].childNodes[0].nodeName, “
”);

sampDiv2.childNodes[1].childNodes[3].style.backgroundColor = “#BFAFB2”;

// Changing element attributes

var nttLogo2 =document.getElementById(‘logo2’);

// Check for attributes

document.write(“Logo has alt : “,nttLogo2.hasAttribute(“alt”), “
”);

// Change attribute

nttLogo2.setAttribute(“alt”, “NTT Logo 2”);

// Get attribute

document.write(“Logo alt Value : “,nttLogo2.getAttribute(“alt”), “
”);

// Get all attributes and print them

var attribList =document.getElementById(‘logo2’).attributes;

for(i = 0; i < attribList.length; i++){

  document.write(“Attribute “, i, ” : “,attribList[i].nodeName, ” : “,attribList[i].nodeValue, “
”);

}

// Add a p element after setting an attribute and text

var paragraph3 =document.createElement(“p”);

paragraph3.setAttribute(“id”, “paragraph3”);

paragraph3.innerHTML = “Proin eget turpis eget quam luctus malesuada ut ac nulla.”;

sampDiv2.appendChild(paragraph3);

// Insert the element before the 1st child

sampDiv2.insertBefore(paragraph3,sampDiv2.childNodes[0]);

// Create a customer object by defining the attributes of John Smith

// The variable is a reference to the object in memory

var cust1 = {

  name: “John Smith”,

  street: “123 Main”,

  city: “Pittsburgh”,

  state: “PA”,

  email: “jsmith@abc.com”,

  balance: 120.50,

  payDownBal: function(amtPaid){

    this.balance -= amtPaid;

  },

  addToBal: function(amtCharged){

    this.balance += amtCharged;

  }

};

// Retrieve the value for the object

document.write(“Customer Name : “,cust1.name, “
”);

// Change the value for the object

cust1.street = “215 Main St”;

document.write(“Customer Address : “,cust1.street, “
”);

// Add a property to cust1

cust1.country = “US”;

document.write(“Customer Country : “,cust1.country, “
”);

// Delete a property

delete cust1.country;

// Cycle through all the properties for the object

for (var prop in cust1) {

    if (cust1.hasOwnProperty(prop)) {

        document.write(prop, “
”);

    }

}

// Check if a property is in an object

document.write(“name in cust1 : “, “name” incust1, “
”);

// Interact with an object using a function

function getInfo(cust){

  return cust1.name + ” lives at “ +cust1.street + ” in “ + cust1.city + ” “ +cust1.state + ” email : “ + cust1.email + ” and has a balance of $” + cust1.balance;

}

document.write(getInfo(cust1), “
”);

// Call object methods

cust1.payDownBal(20.50);

cust1.addToBal(10.00);

document.write(getInfo(cust1), “
”);

// Create an object constructor

function Customer(name, street, city, state,email, balance){

  this.name = name;

  this.street = street;

  this.city = city;

  this.state = state;

  this.email = email;

  this.balance = balance;

  this.payDownBal = function(amtPaid){

    this.balance -= amtPaid;

  };

  this.addToBal = function(amtCharged){

    this.balance += amtCharged;

  };

}

var cust2 = new Customer(“Sally Smith”,“234 Main”, “Pittsburgh”, “PA”,“ssmith@abc.com”, 0.00);

cust2.addToBal(15.50);

// Define a shared prototype property for all objects

Customer.prototype.isCreditAvail = true;

// We define prototype methods that are shared by every object created

Customer.prototype.toString = function(){

    return this.name + ” lives at “ + this.street+ ” in “ + this.city + ” “ + this.state + ” email : “+ this.email + ” and has a balance of $” +this.balance.toFixed(2) + ” Creditworthy : “ +this.isCreditAvail;

};

document.write(cust2.toString());

Enter your name:

Enter your street address:

Enter your city:

Enter your state code:

Enter your phone number:

Enter your email:

function editNodeText(regex, input, helpId,helpMessage)

{

  // See if the info matches the regex that was defined

  // If the wrong information was entered, warn them

  if (!regex.test(input)) {

    if (helpId != null)

      // We need to show a warning

      // Remove any warnings that may exist

      while (helpId.childNodes[0]){

        helpId.removeChild(helpId.childNodes[0]);

      }

      // Add new warning

      helpId.appendChild(document.createTextNode(helpMessage));

    } else {

      // If the right information was entered, clear the help message

      if (helpId != null){

        // Remove any warnings that may exist

        while (helpId.childNodes[0]){

          helpId.removeChild(helpId.childNodes[0]);

        }

      }

    }

}

// inputField – ID Number for the html text box

// helpId – ID Number for the child node I want to print a warning in

function isTheFieldEmpty(inputField, helpId){

  // See if the input value contains any text

  return editNodeText(/^[A–Za–z\.\‘ \–]{1,15}\s?[A–Za–z\.\‘ \–]{1,15}\s?[A–Za–z\.\‘\–]{1,15}/, inputField.value, helpId, “Please enter a valid name.”);

}

// inputField.value – Value typed in the html text box

function isAddressOk(inputField, helpId) {

  return editNodeText(/^[A–Za–z0–9\.\‘ \–]{5,30}$/, inputField.value, helpId, “Enter a Street (Ex.1234 Main St.)”);

}

function isStateOk(inputField, helpId) {

  returneditNodeText(/^A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]$/, inputField.value,helpId, “Enter a State Code in Uppercase (Ex.NY, PA, CA)”);

}

function isPhoneOk(inputField, helpId) {

  return editNodeText(/^([0–9]( |–)?)?(\(?[0–9]{3}\)?|[0–9]{3})( |–)?([0–9]{3}( |–)?[0–9]{4}|[a–zA–Z0–9]{7})$/, inputField.value,helpId, “Enter a Phone Number (Ex.412-828-3000)”);

}

function isEmailOk(inputField, helpId) {

  returneditNodeText(/^[A–Za–z0–9._–]+@[A–Za–z0–9.–]+\.[A–Za–z]{2,4}$/, inputField.value, helpId, “Enter an Email (Ex. derekbanas@newthinktank.com)”);

}

// Through exception handling we can catch and manage errors rather then

// crashing by surrounding problem code in a try block and handling it

// in a catch block

var custArray = [“Tom”, “Bob”, “Sally”, “Sue”];

var getCust = function(index){

  if(index > custArray.length){

    throw new RangeError(“Index must be >= 0 and <= “ + custArray.length );

  } else {

    return custArray[index];

  }

}

try {

  document.write(“Customer : “, getCust(5),“
”);

}

catch(ex){

  if (ex instanceof RangeError){

    document.write(ex.message + “
”);

  }

}

  

I hope you liked it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s