Basic Methods

String Methods

Basic Methods

🙋 Need help? Ask an expert now!

Below are some basic methods that can be used with strings. The .length property as well as the indexer and the charAt() methods are all string properties/methods that you will be using in the future. The syntax of the following properties and methods are shown below.

string.length

  • returns the number of characters in the string

Indexer (string[index])

  • gets a single-character string at location the index
  • index starts from 0
  • if index is outside the range of string characters, the indexer returns undefined

charAt(index)

  • gets a single-character string at location index
  • works similarly to the indexer

The three properties and methods are shown in the sample code above. The property str.length returns the length of the string, which is 12. Note that the space bar as well as the exclamation mark count towards the total length of the string. The indexer returns the character at the specified index, which is why 'H' is printed. The charAt() method does the exact same thing and prints the character at index 0. If the index used in the indexer or in the charAt() method is not an appropriate index in the string, executing it will return undefined.

Edit Me on GitHub!

Application Question

Consider the following statement:

var str = "Hello World!";

What is the length and the last index of the string str?