JavaScript String Methods

Your beginner friendly guide to JavaScript String Methods! Each section will explain what each string method does. You can then enter your own parameters for each argument of each method. The aim is to try to enter different parameters until you find an error. Look out for these errors when you use these methods in your future code!

variable.charAt()

This method will return the character at the index number put between the brackets.

The syntax for this method looks like this: word.charAt(indexNumber)

Remember - computers count index numbers from 0! So if the index number is 2, it will count: 0, 1, 2 (Meaning you will get the 3rd character).

If charAt() cannot perform its function, it will return an empty string.

Output:

variable.length

This method will return the length (number of characters) of the value of the variable. It takes no parameters.

The syntax for this method looks like this: word.length()

For length, the computer counts from 1 (1 = first character). It only counts from 0 in the context of index numbers.

If any characters outside the Basic Multilingual Plane (BMP) are used (like Emojis) it could provide an inaccurate reading (as it counts Emojis as two characters).

Output:

variable.indexOf()

This method will return the index of only the FIRST match of the character put in the brackets.

The syntax for this method looks like this: word.indexOf(character, index)

This method is case sensitive, and returns -1 if no match is found. It searches the word from left to right.

A second argument can be used called: index. This lets you choose where indexOf() starts it's search! If this is empty, the default is 0 (the beginning). Negative numbers are treated as 0.

Output:

variable.lastIndexOf()

This method will return the index of only the LAST match of the character put in the brackets.

The syntax for this method looks like this: word.lastIndexOf(character, index)

This method is case sensitive and returns -1 if no match is found. It searches the word from left to right.

A second argument can be used called: index. You can choose where lastIndexOf() starts it's search! If this is empty, the default is +infinity (the end up until the beginning). Negative numbers are treated as 0.

Output:

More methods coming soon!