What is the Substring Method?
The substring method takes two arguments:
- The start index of the character of the string to start extracting (Tip: this includes spaces!)
- The end index of the character of the string to stop extracting (again, includes spaces) This is optional
Substring does not modify the original string.
const name = "James King"; const firstName = name.substring(0, 5);
The result of firstName is James. Let’s find out why.
The example above has us declaring a string constant, name, and its value is a string of my full name.
Substring selects the characters between the specified index arguments. The end index value is not included in the returned string from substring. Therefore, “dog”.substring(0,1) will return only ‘d’.
As a result, that’s what will be returned from the substring method and assigned to the firstName constant.
Example: Return All Characters After a Character in a String
const todo1 = "01 - Pick up dry-cleaning"; const todo2 = "02 - Go food shopping"; const todo1Task = todo1.substring(5); const todo2Task = todo2.substring(5);
The example above shows how you can return the rest of the string after a specified starting index.
This is good if your strings are all formatted in a certain way, or you don’t know how long your strings are, or you have multiple strings that are all different lengths.
Let’s explore how to remove characters from the end of a string using a reverse index.
We pass in the length of the whole string minus 10 characters, which is the length of the string that we want to extract. The second argument takes the whole length of the string as we want to end at the very last character of it.
💬 Leave a comment