split and join
JavaScript · Unit 6: Strings
- Full plan
- JavaScript
- 10 exercises
split(cut) breaks a string apart and returns an array.
With " " it cuts at the spaces, and with "," at every comma.
const phrase = "I like ice cream";
const words = phrase.split(" ");
console.log(words);
console.log(words.length);Prints
[ 'I', 'like', 'ice', 'cream' ] 4
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Predict the output
What does this code print?
3. Multiple choice
What does this code do?
4. Predict the output
What does this code print?
5. Find the bug
This program should print "ham eggs tea". Which line has the error?
6. Complete the code
Complete the function that counts the words in a sentence.
7. Predict the output
What does this code print?
8. Put the lines in order
Order the function that swaps the spaces in a sentence for commas.
9. Find the case that fails
countWords(phrase)should return how many words the sentence has, or 0 if the sentence is empty. Which call breaks it?10. Write the code
Write
initials(name), which returns the initials in capitals. For example,initials("ann marie reed")gives"AMR". Hint:w[0].toUpperCase()is the first letter of a word, in uppercase.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.