JavaScript
JavaScript String Type
Split
We can split a string into a list
(array) of substrings by using
the split method. This method takes an optional seperator string or
RegExp parameter which determines when to split and an optional rarely
used limit integer parameter that limits the maximum amount of times
we search for the seperator and split the string.
The optional seperator defaults to the entire given string and therefore returns an array with one element: the original string. The limit defaults to infinity.
An empty string seperator "" will split the string into individual
characters.
const ingredients = "Brown sugar, 2 eggs, vanilla extract"const split = ingredients.split(',')console.log(split) // [ "Brown sugar", " 2 eggs", " vanilla extract" ]
Read more on MDN
String.prototype.split()
Test yourself
Description
Define a new function with the name
words
that takes a single string input parameter (a sentence) and returns the number of words in the sentence.
Tips:
- Arrays have a
lengthproperty.
Tests
- 1
You should define a function named
words. - 2
words("I see no value in modest ambitions.")should return7. - 3
words("lowerCamelCase")should return1. - 4
words("The heart is neither given nor stolen. The heart surrenders.")should return10. - 5
words("Wise words are like arrows flung at your forehead. What do you do? Why, you duck of course.")should return18.