课程: JavaScript Practice: String Manipulation

Solution: Split your email list - JavaScript教程

课程: JavaScript Practice: String Manipulation

Solution: Split your email list

- [Instructor] In this challenge, we're given a string with a list of emails. Most likely we will want to use this data to iterate over it and display it on a page. When it's in a string as a list like this, it can be really, really difficult to do this. So this is where the string method "split" comes in really, really handy. The split method splits a string based on the arguments provided and returns an array. Split has two parameters, separator and limit, which is optional. The separator lets the method know where you want to divide up the string, and then the limit allows you to specify if there's a limit to the number of entries in that array. So here our task is to make sure the commas are removed from the list. Let's go ahead and start with our function on line 10, "splitEmails", that takes the argument "emailList". We'll start on line 12 with our "return" and then "emailList". We'll go ahead and apply the string method "split" here. Now we know that we want to split this string up by comma, and what we'll actually need to do is not only have just the comma here, but also a space after the comma because we want to remove any white space and just have the emails. Before we get to our solution, let's remove that space and let's just run this and see how it's returned. So you can see that the first entry looks good. There's no extra spaces, none of that, because we were splitting with the comma and there's no comma at the beginning of the first entry, but every entry thereafter has that empty space at the beginning, and that's not what we wanted. So that's why in our solution here, we're going to add this comma and then a space to make it nice and clean. So let's rerun it. And now we can see that the code return this nice array with no extra spaces and it looks really nice. So great work on this. Excellent job.

内容