How to turn a JavaScript string into an array - Kevin Chisholm Video

Опубликовано: 24 Январь 2018
на канале: Kevin Chisholm
1,655
15

https://blog.kevinchisholm.com/?s=array


In this video, I’ll show you how to turn a JavaScript string into an array.

In JavaScript, every string has a split method, which allows you to turn that string into an array. Here I have a string that says I want to be an array. So if I call the split method and pass it an empty string, then every character or letter in the string becomes an element in the array.

That’s probably not the most practical use of this method. So let’s try something a little bit more typical. So here I’m passing it a space as a separator. So then I’ll probably wind up with every word being an element in the array. And that’s what I get. There are six words in the string, so I wind up with an array with six elements.

But we can also do some more interesting things. For example, if I were to pass the string “ be ” what’s going to happen is it’s going to split on that, so I’ll get a two element array. The first element will be the string “I want to,” and the second element will be the string “an array.”

So here’s my two element array, and the first one is “I want to,” and the second one is “an array.” I’m splitting on the string “ be ”. And you can also do some kind of crazy stuff; for example if I split on the letter “a,” I get a pretty wacky array because every time it finds the letter “a,” it removes that letter and creates a new array element.

So most likely you’re going to split on something like a space, which allows you to convert every word in the string into an array. It’s really up to you, but just know that what you pass to the split method determines how the string is split. But ultimately, it returns an array of elements and the elements are the various characters in that string.

If you found this video helpful, you can subscribe to my channel by clicking the red "Subscribe" button right under the video. You can also take a look at my blog, where there are many articles and tutorials about web development.

Thanks very much for watching.