3.1 Splitting - Video Tutorials & Practice Problems
Video duration:
2m
Play a video:
<v Presenter>The entire last chapter</v> was concerned with strings. So, let's start with strings and talk about how to turn a string into an array. Suppose we've got a string of words, separated by some standard separator, such as a space, ant bat cat. We can turn this into an array by using the split method, which takes in a string that we use as a separator. In this case, I'm just gonna use the space. And the result looks like this. So this is an array of three elements, ant, bat, cat. Split is really useful. It's the kind of thing that is commonly used when processing texts. It's extremely common in things like web development and shell scripting. So let's take a look at some other ways of splitting. We can split on other strings. Suppose that we have comma delimited texts like this. We can split on comma, get the same result. We might have a string like this, ant, bat, cat, with comma space. So if we want to split on... Well, what happens if we split on comma here? You can see that we get ant, but then space bat and space cat, as cool as that might sound, (laughs) it's not what we want usually. So let's put in a comma space, and we get the same thing we got before. We can see that split splits on arbitrary strings. Just one final example. Suppose we say, hey, where these things are separated by the string hey. One common technique across a variety of different languages is to convert a string into an array of characters by splitting on the empty string, for example, can split badger into its constituent characters like this. Another really common task is to split a string on white space, so that it can handle not just spaces like this here, but also tabs, and even new lines. That requires a little bit more advanced work though, in JavaScript. And we'll be covering that in chapter four when we discuss regular expressions.