When you’re programming, it’s common to see cases where you need to get some text from a larger string. Say you want to get a user’s first and last name from one string separately. How would you go about getting that information from a string?
Before we start looking at the split() and slice() 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.
var new_list = text.split(character, limit);
You must assign the output of the split() method to a variable. This is because split() creates a new list. It does not modify your existing string.
Say that a user has given us their first and last names. We store this information in one string. To get the user’s first and last names separately, we could use the split() method.
For example, when a user signs in to their account, we may want to say “Hello, [first name]” instead of displaying their full name.
We’re going to use a white space character (which is the space character) to separate out our string:
var fullName = “Forename Surname”; var fullNameSplit = fullName.split(“ “); console.log(fullNameSplit);
This code returns the following:
This code returns:
The split() method returns an array from which we can retrieve individual values. Each array element corresponds with a word in our string. We retrieved the value with the index position 1 from our array.
You can use the split() method to move the contents of a string into an array. Consider the following code:
var name_as_list = name.split(); console.log(name_as_list);
Our code returns: “Forename Surname”. We did not specify a separator character which means that multiple substrings are not created. We now have an element consisting of the entire string stored in the variable name_as_list.
The split() method divides a string into a list of substrings. It is used to make individual words or values in a string accessible by indexing. split() can separate out a string by any character, such as a white space or a comma.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.