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 length property.

Tests

  1. 1 You should define a function named words.
  2. 2words("I see no value in modest ambitions.") should return 7.
  3. 3words("lowerCamelCase") should return 1.
  4. 4words("The heart is neither given nor stolen. The heart surrenders.") should return 10.
  5. 5words("Wise words are like arrows flung at your forehead. What do you do? Why, you duck of course.") should return 18.
Editor