Programming Fundamentals/Strings/JavaScript

From Wikiversity
Jump to navigation Jump to search

strings.js[edit]

// This program splits a given comma-separated name into first and last name
// components and then displays the name.
//
// References:
//   https://www.mathsisfun.com/temperature-conversion.html
//   https://en.wikibooks.org/wiki/JavaScript

main();

function main() 
{
    var name;
    var last;
    var first;
    
    name = getName();
    last = getLast(name);
    first = getFirst(name);
    displayName(first, last);
}

function getName()
{
    var name;
    var index;
    
    do
    {
        name = input("Enter name (last, first):");
        index = name.indexOf(",");
    } while (index < 0);

    return name;
}

function getLast(name)
{
    var last;
    var index;

    index = name.indexOf(",");
    if(index < 0)
    {
        last = "";
    }
    else
    {
        last = name.substring(0, index);
    }
    
    return last;
}

function getFirst(name)
{
    var first;
    var index;

    index = name.indexOf(",");
    if(index < 0)
    {
        first = "";
    }
    else
    {
        first = name.substring(index + 1);
        first = first.trim();
    }

    return first;    
}

function displayName(first, last) 
{
    output("Hello " + first + " " + last + "!");
}

function input(text) {
  if (typeof window === 'object') {
    return prompt(text)
  }
  else if (typeof console === 'object') {
    const rls = require('readline-sync');
    var value = rls.question(text);
    return value;
  }
  else {
    output(text);
    var isr = new java.io.InputStreamReader(java.lang.System.in); 
    var br = new java.io.BufferedReader(isr); 
    var line = br.readLine();
    return line.trim();
  }
}

function output(text) {
  if (typeof document === 'object') {
    document.write(text);
  } 
  else if (typeof console === 'object') {
    console.log(text);
  } 
  else {
    print(text);
  }
}

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own JavaScript compiler / interpreter / IDE.

See Also[edit]