Javascript Notes – String Properties

.indexOf

If you are looking to find a certain character or set of characters in a string you can use the .indexOf property to return the position of the character in integer format. For example

var myName = "My Name is Nick Coughlin";

myName.indexOf("N");

-> 11

Will return 11 because that is the position in the string of the letter N which is what we were searching for. You can also search for a set of character such as is.

var myName = "My Name is Nick Coughlin";

myName.indexOf("is");

-> 8

You can also use this property to check whether a character or string of characters is inside of a string using this method. If the character or string is not inside of the string the return will be -1

var myName = "My Name is Nick Coughlin";

myName.indexOf("Max");

-> -1

And therefore we can simply check to see if it is true that the .indexOf is ===-1. If it is then the character you are searching for is not present.

.length

This will return the length of the string. For example:

.charAt()

This will select the character at whatever index position you specify in the parentheses:

.toUpperCase()

Will capitalize a string.

This can be combined with .charAt to select and capitalize a specific letter. For example:

.slice()

This property will return the string starting from the index which is chosen. Essentially slicing off the characters at the front.

.replace

Replace a character, or set of characters in a string with another character.