Calculating Univeral Userids - JavaScript String Handling


The following code calculates the universal userid given the person's name.


/* This script demonstrates a number of string methods by asking for the users name, and then calculating their "universal" id */

var full_name = prompt("Enter full name:", "John J. Smith");

// Pickup the initials
var initials = "";
var i= full_name.indexOf(" ");
var j = 0;
while ( i!= -1) //Still looking for the last name
 {initials = initials + full_name.charAt(j);
  j= i+1;
  i= full_name.indexOf(" ",j);}

var last_name = full_name.substring(j);

var userid = (initials + last_name).toLowerCase();

if (userid.length > 8) userid= userid.substring(0,8);

// Report the results

if (userid=="") // No name given or calculated
  document.write('"' + full_name + '" has no universal userid<P>')
else
  document.write(full_name.bold() + "'s universal userid is " +                  userid.bold().italics()+"<P>");

// Output A link to go to UW's home page

document.writeln("UW Home Page".link("http://www.uwaterloo.ca"));


Run the program

Notes:

  1. Comments
  1. While loop
  2. Methods

Back