JavaScript Examples

Dave Braunschweig

Strings

// This program demonstrates string functions.

main();

function main()
{
    var str = "Hello";

    output("string: " + str);
    output("string.toLowerCase(): " + str.toLowerCase());
    output("string.toUpperCase(): " + str.toUpperCase());
    output("string.indexOf('e'): " + str.indexOf('e'));
    output("string.length: " + str.length);
    output("string.replace('H', 'j'): " + str.replace('H', 'j'));
    output("string(substring(2,4): " + str.substring(2, 4));
    output("string.trim(): " + str.trim());

    var name = "Bob";
    var value = 123.456;
    output(`string.format(): ${name} earned $${value.toFixed(2)}`);
}

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

Output

string: Hello
string..toLowerCase(): hello
string.toUpperCase(): HELLO
string.indexOf('e'): 1
string.length: 5
string.replace('H', 'j'): jello
string(substring(2,4): ll
string.trim(): Hello
string.format(): Bob earned $123.46

Files

Note: For security reasons, JavaScript in a browser requires the user to select the file to be processed. This example is based on node.js rather than browser-based JavaScript.

// This program demonstrates reading a text file with exception handling.

const fs = require('fs');

main();

function main() {
    const filename = "temperature.txt";
    readFile(filename);
}

function readFile(filename) {
    try {
        const text = fs.readFileSync(
            filename, 
            {encoding:"utf8"});

        const lines = text.split("\n");

        for (const line of lines) {
            console.log(line);
        }
    } catch (exception) {
        console.log(exception)
    }
}

Output

Celsius,Fahrenheit
0,32
10,50
20,68
...
80,176
90,194
100,212

References

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Programming Fundamentals Copyright © 2018 by Authors and Contributors is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book