OneBite.Dev - Coding blog in a bite size

split a string by empty space in Javascript

Code snippet on how to split a string by empty space in Javascript

  const str = 'Hello world!';
  
  const words = str.split(' ');

This code uses the JavaScript split() method to take a string, ‘Hello world!’ in this example, and split it into an array of words based on the empty space separator.

The first line of code creates a variable, str, that stores the string value ‘Hello world!‘.

The second line of code creates another variable, words, which stores the result of the split() method. The split() method takes a string as its argument (in this example the string stored in the str variable) and splits it into an array of words, separating words by the empty space separator. The result of the split action is stored in the words variable.

javascript