5. String Methods

Objective:Β By the end of this checkpoint you will learn how to manipulate Strings using out of the box JavaScript String methods

Key Terms

  • String Method
  • Split Method
  • Substring Method
  • Length Property
  • IndexOf Method
  • LastIndexOf Method
  • Replace Method
  • CharAt Method
  • CharCodeAt Method
  • Concatenating Method
  • Slice Method
  • Substr Method
  • Letters to Uppercase Method
  • Letters to Lowercase Method

JavaScript String Methods

Convert to String

You can convert a Number, Boolean, or an Object to a String:

Alternatively, you can also achieve the same result with the String() method:

Nicholas Zakas, in Professional JavaScript for Web Developers, says: β€œIf you’re not sure that a value isn’t null or undefined, you can use the String() casting function, which always returns a string regardless of the value type.”


Split a String Into Multiple Substrings

To separate a string into an array of substrings, you can use the split() method:

As shown in the last line, a second optional argument limits the array to the number of items specified by the argument.


Get the Length of a String

To find out how many characters long a string is, use the length property:

Locate a Substring within a String

There are two methods for doing this.

  • Using indexOf() method:

The indexOf() method starts searching for the substring (the first argument passed in) from the beginning of the string. Then returns the position of the start of the first occurrence of the substring.

  • Using lastIndexOf() method:

The lastIndexOf() method is exactly the same except it returns the starting position of the last occurrence of the passed in substring.

In both methods, if the substring is not found, the returned value is -1 and both allow an optional second argument indicating the position in the string where you want to start the search. So with a second argument of β€œ5”, indexOf() method starts searching at character 5, ignoring characters 0-4, while lastIndexOf() method starts searching at character 5 and goes in reverse, ignoring characters 6 and above.


Replace a Substring

To replace part or all of a string with a new string, you can use the replace() method:

The first argument is the substring you want to replace and the second argument is the new substring. This will only replace the first instance of the matched substring.

To replace all instances of the matched substring, use a regular expression with the global flag:

The second argument can include special replacement patterns or can be a function. More information on Regular Expressions can be found in this MDN reference.


Find the Character at a Given Position

To find out which character is at a specified position, you can use the charAt() method:

As is often the case in JavaScript, the first position in the string is referenced with β€œ0” instead of β€œ1”.

Alternatively, you could use the charCodeAt() method, which gives you the character code, instead of the character itself:

Notice that the character code for the uppercase β€œF” (position 11) is different from the character code for the lowercase β€œf” (position 7).


Concatenating Multiple Strings

For the most part, when you concatenate strings, you’ll use the addition operator (+). But you do also have the option to use the concat() method:

You can also pass multiple strings into it, and all will be appended (in the order they appear) to the original string. For example:

Slice a String (Extract a Substring)

There are three different ways to create a new string value from part of another string:

  • Using the slice() method:

  • Using substring() method:

For both slice() and substring() methods, the first argument is the character at which to begin the substring (again using zero-based numbering) and the second argument (which is optional) is the character in the string after you want the substring to end. So in the examples above, the arguments β€œ5, 10” mean characters 5 through 9 are β€œsliced” to create the new string.

  • Using substr() method:

For the substr() method, once again, the first argument represents the character that begins the new string and the second argument is optional. But this time, the second argument represents the total number of characters that should be included, starting with the character in the β€œ5” position.


Convert a String to Uppercase or lowercase

There are four methods that do case conversion. Two for converting a string to all UPPER CASE:

And two for converting a string to all lower case:

Generally, the results between the β€œlocale” method and the non-locale method are the same. But according to this MDN reference guide, β€œfor some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result.” Zakas’ book says β€œif you do not know the language in which the code will be running, it is safer to use the locale-specific methods.”


Pattern Matching

Matching a pattern within a string can be done using one of two methods, which basically work the same way.

The match() method is called on a string and is passed a regular expression:

And the exec() method is called on a RegExp object and is passed the string:

For both methods, only the first matched occurrence is returned. If no match is found, it will return null.

You can also use the search() method, which accepts a regular expression as the only argument and returns the location of the first occurrence of the pattern:

If no match is found, the method returns -1.


Compare Two Strings for Sort Order

You can compare two strings to see which one comes first alphabetically using localeCompare, with three possible return values:

As shown above, a negative number is returned if the string argument comes after the original string. A positive number is returned if the string argument comes before. And 0 is returned if the strings are equal.