When you’re programming, it’s common to see cases where you need to get some text from a larger string, or split up that string into multiple parts. If you want to get a user’s first and last name, how would you go about getting that information from a string?
That’s where the
slice() functions come in. These functions allow you to manipulate a string to specific certain information. For example, you could use
split() to divide a user’s name into two strings: one for the user’s first name, and one for their surname. Or you could use
slice() to get certain characters from a larger string.
- Speak to a career coach to get guidance
- Coaching sessions are free and always will be
Before we start looking at the
splice() functions, we should remind ourselves how strings work. Strings are a sequence of one or more characters that may include letters, symbols, or numbers.
Each character in a string can be accessed using its index number, starting with 0. Let’s use an example to illustrate how a string is indexed:
As you can see, the first character in the string is “H,” which has an index value of “0”. The last character is “e,” which has an index value of “10.” Note that the space between the two words also has an index value.
If we want to access a particular character using its index value, we can use square bracket notation, like so:
var name = “John Appleseed”; console.log(name)
This code would return
n, which has the index value of
3. You can also use the
indexOf() function to return the index number for the first instance of a character in a string.
This code would return
Let’s say we need a specific section of text from our broader string: how do we do that? Now that we know the basics of strings, we can use the
slice() function to gather text from a string.
Slice extracts the characters between two index numbers. The first parameter is the starting index number, and the second is the index number where your substring should end. Here’s an example:
“John Appleseed”.slice(5, 10);
This would return
Apple, all letters starting at the index of
5 and ending with the character before the last index in our string:
You can also specify a single parameter if you want to return everything from that parameter to the end of the string. Here’s an example:
This would get every character starting with the index value
5 from the original string and return it into a new string:
slice() will help return string values based on index numbers. You can use
indexOf() as we discussed earlier to return the index numbers of a particular character in a string.
split() function takes in one parameter, which is how the string will be split. Here’s an example of the
split() method in action, separating the string using a whitespace character (which is the space character):
var fullName = “Forename Surname”; var fullNameSplit = fullName.split(“ “); console.log(fullNameSplit);
This code would return the following:
This would return:
If there is no parameter given to