Strings

Page section: posts

Strings can be defined using single quotes, double quotes or backticks.

With backticks they are referred to as template literals. You can do more with these like including a line break. With quotes the line break is not recognized.

Two or more regular strings can be joined together (concatenated) using the + operator or joined to other variables.

If you use backticks (template literals) you tend to use one long string with variable names and other JS inside curly braces with a dollar sign: ${myVariable}

let joined = "My worm is called " + name;

Computation inside strings

If you use backticks (template literals) you can compute within a string:

let divide = `Half of 100 is ${100 / 2}.`;

Press to calculate using the above code.

The answer is ??

Changing case

You can change the case of variables using the toLowerCase() or toUpperCase() methods. Note the camel case and brackets.

Example of a variable:

let countries = worldnames.toLowerCase();

With an array item:

alert(monick[2].toUpperCase());

With a string and then a variable:

if ("My Donkey Came in".toLowerCase === donkey) {
    alert(donkey.toUpperCase());
}

The escape character \

Because quotes define regular strings how do you use quotes inside a string?

One way is to use the escape backslash character \.

let quoteProblem = "He said, "This will not work" to me.";

The fix using the escape character (backslash) BEFORE the quotes:

let quoteProblem = "He said, \"This is fine\" to me.";

Other escape codes

code meaning
\' escape single quote
\\ escape backslash character
\n add new line character
\r add carriage return character
\b add backspace character
\f add form feed character

Concatenating strings

You can use the + sign to join two value let p = xxu + "firebeans" or use +=:

let xxu = "The orange smells";
xxu += "firebeans";

The second line will add the string firebeans to the variable xxu. In other words it means:

xxu = xxu + "firebeans";

Template strings

Another way of combining variables in strings is to use template strings aka template literals. These are enclosed in backticks and variable names are inside surrounded with curly braces and preceded with a dollar sign: ${exampleVar}.

const myString = 'Some text';
const strLength = myString.length;

const sentence = `${myString} is ${strLength} characters long`;

Template literals are useful for injecting HTML into a page.

const dynamicPage = `
  <h1>${title}</h1>

  <time>Created on ${date}</time>

  <section class="content">${pageContent}</section>
`;

Finding the length of a string

The .length property will give you the string length.

const myString = 'How many characters are there?';

myString.length

// 30

Getting the nth character of a strings

Like arrays you can access a specific character by counting from the left starting with zero.

let nb = "My numbat"

nb[0] will grab the first character M, nb[2] will get the third letter etc.

To get the last letter:

nb[nb.length - 1];

The -1 account for the fact the counting start at zero.

Declaring multiple strings at once

let species = "numbat", family = "marsupial", region = "Australia";

You can also create an empty string:

let species, family, region;

then:

species = 'numbat';
family = 'marsupial';
region = 'Australia';

NB. Spaces are counted too.

String methods

A method is a function that is bound to an object. Like ordinary functions methods are followed by brackets.

myString.toUpperCase();

This method does not change the original value of the string. You would need to write:

myString = myString.toLowerCase();

// or store in a new value

let newString = myString.toLowerCase();

Methods can contain arguments inside the brackets.

myString.indexOf('a');

This will find the position of the first a character in the string.

To find the position of the last letter a use myString.lastIndexOf('a');

Other string methods include

.slice(4, 8) which copies the characters from the 3rd postition to the 6th.

.substr(4, 8) is very similar except the second argument counts 5 from the first argument.

The .replace('a', 'c') method will replace the first instance of a letter a with the letter ‘c’. To replace all the letters use .replaceAll.

myString.replaceAll('cat', 'wolf');

includes()

Another string method is .includes() used to see if a string includes a substring.

alert(nb.includes('bat'))

The .includes() method can also be used on arrays to match elements of the array.

myArray = ['one', 'two', 'three'];

myArray.includes('two');

// output: true

Table of Contents