Spelchan.com Logo

From Scratch Web Games: A Beginners Guide to Game Development using HTML, CSS, and JavaScript

Chapter 4.8: Strings

Strings, are a term used for a block of text. As web pages often deal with text, it is not surprising that we have a class dedicated to text. Strings are called Strings because you are “stringing together a bunch of characters.” While we often treat strings as a primitive type, largely because they are used so often, they really are an object. You do not need to understand objects to use them, though we will be covering objects in chapter 7.

If you look at the image below, you will see how a computer stores a string. It is just a series of characters. Each character has an index (the number above the box) which can be used to find a particular character or used to create sub-strings. The important part that you need to understand is that the first character is at index 0. This is not because computer scientists have a bad habit of counting from 0, though that does tend to be the case. If you think of the index as an offset into the string of characters, the first character has no offset.

Image of how strings are stored in memory

In JavaScript, strings are immutable. This means that once you have created a string, you can not change that string. Instead, operations on strings create new copies of the string. If you are no longer using the old version of the string, it will be put into the garbage and eventually freed up when more memory is needed. This garbage collection happens in the background, so you normally do not need to think about it. You may be wondering why we want immutability. Because we can have multiple references to the same string that means that if it was possible to change the string, all references to that string would be changed which could lead to disaster.

One common thing that we want to do with strings is to join them together, or more precisely, concatenate them. This is such a common activity that JavaScript has a special operator for doing this. That being the + operator. Adding a number to a string concatenates the string equivalent of the number to the end of the string. This can be a problem area for JavaScript as since JavaScript uses dynamic typing, it will convert types on you. This can result in some strange bugs. For example, if JavaScript thinks the variable num is the string “2” then the statement num = num + 2; would result in the value of “22”.

One question is that if we put strings into quotes, how do we get a quote into a string? The answer is we use an escape character. The \ character indicates that the next character is part of the string so \\ would result in a backslash, \" is a quote, and \' is a single quote. There are some additional characters that you can use, with \n indicating a new line, \t indicating a tab and \u followed by a Unicode hexadecimal number indicates a specific Unicode character.

Strings have a library of operations that can be performed on them. These are called by using a period after the string you wish to call the operation with. For example, if you had a string named str and wanted to get an upper-case version of that string you would write:

Let upperStr = str.toUpperCase();

Here is a list of commonly used String methods with some sample code. For the sample code we are using the following variables:

let s = "Hello World!";
let myNameIs = "My name is ";
let billy = "Billy"
let lotsOfSpaces = " X ";
  • charAt(index) returns character at index (nrgative counts back from end)
    console.log("s.charAt(6) is " + s.charAt(6)); // W
  • charCodeAt(index) same as charAt but returns UTF-16 code
    console.log("s.charCodeAt(6) is " + s.charCodeAt(6)); // 87
  • concat(str) same as adding strings
    console.log("myNameIs.concat(billy) is " + myNameIs.concat(billy))
    // "My name is Billy"
  • endsWith(str) checks if last characters match string
    console.log("s.endsWith(\".\") is " + s.endsWith(".")) // false
    console.log("s.endsWith(\"!\") is " + s.endsWith("!")) // true
  • includes() checks if provided string contained within string
    console.log("s.includes(\"World\") is " + s.includes("World"))
    // true
    console.log("s.includes(\"Billy\") is " + s.includes("Billy"))
    // false
  • indexOf(str) finds first index of provided string with optional start index, -1 if not in string
    console.log("s.indexOf(\"l\") is " + s.indexOf("l")) // 2
  • lastIndexOf(str) same as index of but from end
    console.log("s.lastIndexOf(\"l\") is " + s.lastIndexOf("l")) // 9
  • replace(str, replacement) replaces occurrences of first string with second string
  • slice(start, end) returns substring between start and ending indexes (not including ending index character)
    console.log("s.slice(6,11) is " + s.slice(6,11)); // "World"
    console.log("s.slice(6, 12) is " + s.slice(6,12)); // "World!"
    console.log("s.slice(6) is " + s.slice(6)); // "World!"
    console.log("s.slice(12, 6) is " + s.slice(12,6)); // ""
  • split(delimiter) breaks string into array based on split string. will cover arrays later.
    console.log("\"a,b,c\".split(\",\") is " + "a,b,c".split(","))
  • substring(start, end) same as slice but will order indexes
    console.log("s.substring(11, 6) is " + s.substring(11,6));
    // "World"
    console.log("s.substring(12, 6) is " + s.substring(12,6));
    // "World!"
    console.log("s.substring(6) is " + s.substring(6)); // "World!"
  • toLowerCase() converts string to lower case
    console.log("s.toLowerCase() is " + s.toLowerCase())
    // "hello world!"
  • toUpperCase() converts string to UPPER CASE
    console.log("s.toUpperCase() is " + s.toUpperCase())
    // "HELLO WORLD!"
  • trim() removes whitespace from beginning and ending of string
    console.log("lotsOfSpaces+\".\" is "+
    lotsOfSpaces+"."); // " X ."
    console.log("lotsOfSpaces.trim()+\".\" is "+
    lotsOfSpaces.trim()+"."); // "X."
  • trimEnd() removes whitespace from ending of string
    console.log("lotsOfSpaces+\".\" is "+
    lotsOfSpaces+"."); // " X ."
    console.log("lotsOfSpaces.trimEnd()+\".\" is "+
    lotsOfSpaces.trimEnd()+"."); //" X."
  • trimStart() removes whitespace from beginning of string
    console.log("lotsOfSpaces+\".\" is "+
    lotsOfSpaces+"."); // " X ."
    console.log("lotsOfSpaces.trimStart()+\".\" is "+
    lotsOfSpaces.trimStart()+"."); // "X ."

You will find that string manipulation is a very important aspect of programming so having a good idea of what is in the string library is handy. Next we will look into how we calculate true and false values, which is the building block to conditional computing.

Chapter contents

Chapter 4 Contents

4.1 Cheat Sheets

A quick summary of the basics of JavaScript.

4.2 History of JavaScript

A brief look at how JavaScript was written in 10 days.

4.3 Comment Controversy

Comments. Why programmers don't write them, and how they should be written

4.4 Variables

Variables are used to store the state of a program.

4.5 (extra) How Computers Represent Data

Bits, Bytes, and data types.

4.6 Math

Math on the computer similar but some symbol differences.

Math functions

Various math operations can be used through the Math class.

4.8 Strings

Strings are what we call blocks of text and are used extensively.

4.9 Calculating true and false

Determining if a conditional expression is true or false

4.10 if (Conditional statements)

Conditional code using the if statement.

4.11 Nested conditions

Coming May 5th, 2024

4.12 Switch statement

Coming May 12th, 2024

4.13 Functions

Coming May 19th, 2024

4.14 Looping

Coming May 26th, 2024

4.15 Nested loops

Coming June 2nd, 2024

4.16 Accessing the Web page

Coming June 9th, 2024

4.17 Events

Coming June 16th, 2024

4.18 Project: Where’s Wendy

Coming June 23rd, 2024

4.19 Project: Where’s Wendy implementation

Coming June 30th, 2024


← previous section
Math Functions
next section →
Calculating Truth
Table of Contents